<?php

namespace app\api\controller\m2979;
use app\api\controller\Base;
use app\common\model\LogSms;
use app\common\model\Module;
use app\userbase\model\Ads as AdsModel;
use app\userbase\model\ArticleColumn;
use app\userbase\model\Nav as NavModel;
use app\userbase\model\Suggestions;
use app\userbase\model\SuggestionsType;
use app\userbase\model\Collection as CollectionModel;
use app\userbase\model\User as UserModel;
use app\common\model\Api;
use app\common\model\DySms;
use app\common\model\EmailSms;
use app\userbase\model\Task as TaskModel;
use service\Str;
use think\Db;
use service\ApiReturn;
use think\helper\Hash;
use think\response\Json;
use app\userbase\model\Certified;
use app\userbase\model\Address as AddressModel;
use app\common\model\Area;
use app\userbase\model\MoneyLog;
use app\userbase\model\Withdraw as WithdrawModel;
use app\userbase\model\WithdrawAccount;
use service\SmsZrwService;
use service\EmailSend;

// require_once("./../extend/qrcode/phpqrcode.php");

/**
 * 用户接口
 * @package app\api\controller\v1
 */
class User extends Base
{
    /**
     * 获取热门城市
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function get_city_list($data = []){

        //查询热门城市
        $return['rm'] = Db::name('china_area')->where('is_hot',1)->field('id,region_code,name,pinyin')->select();
        $arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        foreach($arr as $k => $v){
            $return['citys'][$k]['flag'] = $v;
            $return['citys'][$k]['city'] = Db::name('china_area')->where('level',2)->where('first',$v)->field('id,first,region_code,name,pinyin')->order('first asc')->select();
        }
        return ApiReturn::r(1, $return, '操作成功');
    }
    /**
     * 获取热门城市
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function get_city_list1($data = []){

        //查询热门城市
        $rm = Db::name('china_area')->where('is_hot',1)->field('id,region_code,name,pinyin')->select();

        return ApiReturn::r(1, $rm, '操作成功');
    }
    /**
     * 手机号一键登录
     * @param string $data
     * @author 李盼望
     * @created 2020/9/5 15:42
     */
    public function mobile_login($data = []) {
        $result = addons_action('Dypnsapi/Dypnsapi/GetMobile', $data);
        if ($result['code']) {
            $mobile = $result['mobile'];

            Db::startTrans();
            try {
                //检查手机号有没有注册
                $map['mobile'] = $mobile;
                $user = UserModel::where($map)->find();
                //查询是否有用户注销信息

                if (!$user) {
                    //不存在直接注册
                    if (isset($data['invite_code']) && $data['invite_code'] != "") {
                        $lastid = Db::name('user_info')->where('invite_code', $data['invite_code'])->value('user_id');
                        if ($lastid) {
                            $user_data['lastid'] = $lastid;
                        }
                    }
                    $nickname = lang('用户') . rand(10000, 99999);
                    $user_data['mobile'] = $mobile;
                    $user_data['real_name'] = $data['real_name'] ?? '';
                    $user_data['client_id'] = $data['client_id'];
                    $user_data['user_type'] = 0;
                    $dafault_avatar = config('web_site_domain') . '/static/admin/images/name.png';
                    $user_data['avatar'] = $data['avatar'] ? $data['avatar'] : $dafault_avatar;
                    $user_data['nickname'] = $data['nickname'] ? $data['nickname'] : $nickname;
                    $user_data['create_time'] = time();
                    $user_data['status'] = 1;
                    $user_data['gender'] = $data['gender'] ? $data['gender'] : 0; //1男 2女
                    $user_data['birthday'] = time();
                    $userlevel_id = Db::name('user_level')->order('aid asc')->value('aid');
                    $user_data['userlevel_id'] = $userlevel_id ? $userlevel_id : 0;

                    //注册账号
                    $result = UserModel::create($user_data);
                    $id = $result->id;
                    if (!$id) {
                        exception(lang('注册会员失败'), -999);
                    }

                    $userassets = Db::name('user_assets')->insert(['user_id' => $id, 'create_time' => time(), 'update_time' => time()]);
                    if (!$userassets) {
                        exception(lang('注册资产信息失败'));
                    }
                    // 新增会员附加信息
                    $userinfo = Db::name('user_info')->insert(['user_id' => $id, 'invite_code' => 'IC00' . $id]);
                    if (!$userinfo) {
                        exception(lang('注册附加信息失败'), -999);
                    }

                    $user = UserModel::where($map)->find();

                    //获取用户附加信息
                    $user_info = Db::name('user_info')->where('user_id', $user['id'])->find();
                    //获取登录需要返回的信息
                    $jsonList = $this->get_login_info($user, $user_info);
                } else {
                    if (!$user['status']) {
                        exception(lang('此用户被禁用，请联系客服咨询'), -999);
                    }

                    $unset_user = Db::table('lb_user_cancel')->where('user_id', $user['id'])->where('status', 2)->order('aid desc')->find();
                    if ($unset_user) {
                        exception(lang('此用户已注销'), -999);
                    }

                    //获取用户附加信息
                    $user_info = Db::name('user_info')->where('user_id', $user['id'])->find();
                    //获取登录需要返回的信息
                    $jsonList = $this->get_login_info($user, $user_info);
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ApiReturn::r($e->getCode(), [], $e->getMessage());
            }
            return ApiReturn::r(1, ['userinfo' => $jsonList], lang('登录成功')); //返回给客户端token信息
        } else {
            return ApiReturn::r(-999, [], $result['msg']);
        }
    }


    /**
     * 获取用户登录信息
     * @param string $data 传入的数据，包含username和password
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user_name_login($data = []) {
        $map = [];
        switch ($data['account_type']) {
            case 'account':
                $map['account'] = $data['account'];
                break;
            case 'mobile':
                $map['mobile'] = $data['account'];
                break;
            case 'email':
                $map['email'] = $data['account'];
                break;
            default:
                return ApiReturn::r(0, [], lang('非法请求'));
                break;
        }
        $map['is_del'] = 0;
        $user = UserModel::where($map)->order('id desc')->find();
        if (!$user) {
            return ApiReturn::r(-999, [], lang('该账号尚未注册'));
        }
        if ($user['status'] == 2) {
            return ApiReturn::r(-999, [], lang('该账号已被禁用'));
        }
        $unset_user = Db::table('lb_user_cancel')->where('user_id', $user['id'])->where('status', 2)->order('aid desc')->find();
        if ($unset_user) {
            return ApiReturn::r(-999, [], lang('此用户已注销'));
        }


        if ($user) {

            $type = 1;
            $time = strtotime(date("Y-m-d"));
            $where[] = ['user_id','=',$user['id']];
            $where[] = ['create_time','gt',$time];
            $where[] = ['type','=',$type];
            $count = Db::name('user_login_info')->where($where)->count();

            if ($count >= member_config("goods.login_count")) {
                return ApiReturn::r(-999, [], '账号已被锁定,请明天再试');
            }
            if (!Hash::check((string)$data['password'], $user['password'])) {
                $now_time = time();
                Db::name('user_login_info')->insert([
                    'mobile' => $user['mobile'],
                    'create_time' => $now_time,
                    'user_id' => $user['id'],
                    'type' => $type
                ]);

                return ApiReturn::r(0, [], lang('账号或者密码错误'));
            }
            if (!$user['status'] || $user['is_del'] == 1) {
                return ApiReturn::r(-999, [], lang('此用户被禁用，请联系客服咨询'));
            }
            // Db::name('user_login_info')->where($where)->delete();
            unset($user['password']);
            //获取用户附加信息
            $user_info = Db::name('user_info')->where('user_id', $user['id'])->find();
            //获取登录需要返回的信息
            $jsonList = $this->get_login_info($user, $user_info);

            return ApiReturn::r(1, ['userinfo' => $jsonList], lang('登录成功')); //返回给客户端token信息
        } else {
            return ApiReturn::r(0, [], lang('该用户不存在'));
        }
    }

    /**
     * 用户使用手机验证码登录
     * @param string $data
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/7 16:31
     */
    public function user_login_bycode($data = []) {
        // var_dump($data);die;
        if ($data['mobile'] != '') {
            $map['mobile'] = $data['mobile'];
            if (!preg_match("/^1\d{10}$/", $data['mobile'])) {
                return ApiReturn::r(-999, [], lang('请输入正确的手机号格式'));
            }
            $logSmsModel = new DySms();
            $verify_info = $data['mobile'];
        } else {
            // var_dump(1111);die;
            $map['email'] = $data['email'];
            if (!preg_match("/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i", $data['email'])) {
                return ApiReturn::r(-999, [], lang('请输入正确的邮箱格式'));
            }
            $logSmsModel = new EmailSms();
            $verify_info = $data['email'];
        }
        Db::startTrans();
        try {
            $result = $logSmsModel->verify_code_m($data['code'], $verify_info, $data['type']);
            if (!$result) {
                exception('登录失败,验证码无效或已过期', -999);
            }

            //查询用户信息
            $map['is_del'] = 0;
            $user = UserModel::where($map)->order('id desc')->find();
            if (!$user) {
                //不存在直接注册
                if (isset($data['invite_code']) && $data['invite_code'] != "") {
                    $lastid = Db::name('user_info')->where('invite_code', $data['invite_code'])->value('user_id');
                    if ($lastid) {
                        $user_data['lastid'] = $lastid;
                    }
                }
                $nickname = lang('用户') . rand(10000, 99999);
                $user_data['account'] = time() . '_' . rand(10000, 99999);
                $user_data['mobile'] = $data['mobile'];
                $user_data['real_name'] = $data['real_name'] ?? '';
                $user_data['client_id'] = $data['client_id'];
                $user_data['email'] = $data['email'] ?? '';
                //$user_data['user_type'] = 0;
                $dafault_avatar = config('web_site_domain') . '/static/admin/images/name.png';
                $user_data['avatar'] = $data['avatar'] ? $data['avatar'] : $dafault_avatar;

                $user_data['nickname'] = $data['nickname'] ? $data['nickname'] : $nickname;
                $user_data['create_time'] = time();
                $user_data['status'] = 1;
                $user_data['gender'] = $data['gender'] ? $data['gender'] : 0;
                $user_data['birthday'] = time();
                $userlevel_id = Db::name('user_level')->order('aid asc')->value('aid');
                $user_data['userlevel_id'] = $userlevel_id ? $userlevel_id : 0;

                //注册账号
                $user_data['user_group'] = 'user';
                $result = UserModel::create($user_data);
                $id = $result->id;
                if (!$id) {
                    exception('注册会员失败', -999);
                }
                $user_source = empty($data['user_source']) ? 'other' : $data['user_source'];
                $userassets = Db::name('user_assets')->insert(['user_id' => $id, 'create_time' => time(), 'update_time' => time()]);
                if (!$userassets) {
                    exception(lang('注册资产信息失败'));
                }
                // 新增会员附加信息
                $userinfo = Db::name('user_info')->insert(['user_id' => $id, 'invite_code' => 'IC00' . $id]);
                if (!$userinfo) {
                    exception('注册附加信息失败', -999);
                }
                $user = UserModel::where($map)->find();

                //获取用户附加信息
                $user_info = Db::name('user_info')->where('user_id', $user['id'])->find();
                //获取登录需要返回的信息
                $jsonList = $this->get_login_info($user, $user_info);
                $zhuce = 1;
            } else {
                if ($user['status'] == 2) {
                    exception('此用户被禁用，请联系客服咨询', -999);
                }

                //$unset_user = Db::table('lb_user_unset')->where('user_id', $user['id'])->where('status', 1)->find();
                //if ($unset_user) {
                //    exception(lang('此用户已注销'), -999);
                //}
                //获取用户附加信息
                $user_info = Db::name('user_info')->where('user_id', $user['id'])->find();
                //获取登录需要返回的信息
                $jsonList = $this->get_login_info($user, $user_info);
                $zhuce = 0;
            }


            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r($e->getCode(), [], $e->getMessage());
        }
        return ApiReturn::r(1, ['userinfo' => $jsonList,'zhuce'=>$zhuce], lang('登录成功')); //返回给客户端token信息
        // } else {
        //     return ApiReturn::r(0, [], lang('该用户不存在'));
        // }
    }

    /**
     * 社会化第三方登录
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/9 22:28
     */
    public function user_social_login($data = [], $user = []) {
        $module  = request()->header('module');
        $extend_info = json_decode($data['extend_info'], true);
        switch($data['third_type']){
            case 'wx_app'://微信app授权
                if (empty($extend_info['unionid']) && empty($extend_info['openid'])) {
                    return ApiReturn::r(0, [], lang('请先授权'));
                }
                $data['unionid'] = $extend_info['unionid'];
                $data['openid'] = $extend_info['openid'];
                break;

            case 'wx_miniapp'://微信小程序授权
                $wechat_config = Db::name('addons')->where('name', 'WeChat')->where('module', $module)->value('config');
                $wechat_config = json_decode($wechat_config, true);
                // dump($wechat_config);die();
                $result = addons_action('WeChat', 'AuthCode', 'get_session', [$extend_info['code']], $wechat_config);
                unset($result['session_key'], $result['watermark']);//删掉微信加密信息
                if(empty($result['openid'])){
                    return ApiReturn::r(0, ['result' => $result], lang('授权信息解析失败')); //返回给客户端token信息
                }
                $result['gender'] = 1;
                $result['nickname'] = '';
                $result['avatar'] = '';
                $data['unionid'] = $result['unionid'];
                $data['openid'] = $result['openid'];
                break;
        }

        $map = [];
        $map[] = ['type','=',$data['third_type']];
        if (!empty($data['unionid'])) {
            $map[] = ['unionid','=',$data['unionid']];
        } else {
            $map[] = ['openid','=',$data['openid']];
        }
        $third_info = Db::name('user_third')->where($map)->find();
        if (!$third_info) {
            return ApiReturn::r(1, ['result' => $data], lang('没有此用户，开始注册绑定跳转'));
        }
        $user = UserModel::where('id', $third_info['user_id'])->find();
        if ($user) {
            Db::startTrans();
            try {
                if (!$user['status']) {
                    exception(lang('此用户被禁用，请联系客服咨询'), -999);
                }
                $user_info = Db::table('lb_user_info')->where('user_id', $user['id'])->find();
                if (!$user_info) {
                    exception(lang('该用户不存在'), -999);
                }
                // 获取登录需要返回的信息
                $jsonList = $this->get_login_info($user, $user_info);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ApiReturn::r(0, [], $e->getMessage());
            }
            return ApiReturn::r(1, ['userinfo' => $jsonList], lang('登录成功')); //返回给客户端token信息
        } else {
            return ApiReturn::r(0, [], lang('该用户不存在'));
        }
    }

    /**
     * 第三方绑定账号，无账号则自动注册绑定
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/10 16:08
     */
    public function bind_third_account($data) {
        $module  = request()->header('module');
        // $data['extend_info'] = urldecode($data['extend_info']);
        $extend_info = json_decode($data['extend_info'], true);
        $map = [];
        switch($data['third_type']){
            case 'wx_app'://微信app授权
                if(empty($data['account']) || empty($data['code'])){
                    return ApiReturn::r(0, [], lang('非法请求'));
                }
                switch ($data['account_type']) {
                    case 'account':
                        $map['account'] = $data['account'];
                        break;
                    case 'mobile':
                        $map['mobile'] = $data['account'];
                        $logSmsModel = new DySms();
                        break;
                    case 'email':
                        $map['email'] = $data['account'];
                        $logSmsModel = new EmailSms();
                        break;
                    default:
                        return ApiReturn::r(0, [], lang('非法请求'));
                        break;
                }

                if ($data['account_type'] != 'account') {
                    $result = $logSmsModel->verify_code_m($data['code'], $data['account'], $data['type']);
                    if (!$result) {
                        return ApiReturn::r(-999, [], '登录失败，验证码无效或已过期');
                    }
                }
                break;
            case 'wx_miniapp'://微信小程序授权
                $wechat_config = Db::name('addons')->where('name', 'WeChat')->where('module', $module)->value('config');
                $wechat_config = json_decode($wechat_config, true);
                $result = addons_action('WeChat', 'AuthCode', 'get_mini_user', [$extend_info['code'], $extend_info['iv'], $extend_info['encrypteddata']], $wechat_config);
                if(empty($result['purePhoneNumber'])){
                    return ApiReturn::r(0, $result, lang('授权失败'));
                }
                $data['account'] = $result['purePhoneNumber'];
                $map['mobile'] = $data['account'];
                $data['source'] = 2;
                break;
        }
        $data['gender'] = empty($extend_info['gender']) ? '' : 0;
        $data['avatar'] = empty($extend_info['avatar']) ? '' : $extend_info['avatar'];
        $data['nickname'] = empty($extend_info['nickname']) ? '' : $extend_info['nickname'];
        $data['unionid'] = empty($extend_info['unionid']) ? '' : $extend_info['unionid'];
        $data['openid'] = empty($extend_info['openid']) ? '' : $extend_info['openid'];

        Db::startTrans();
        try {
            $map['is_del'] = 0;
            $user = UserModel::where($map)->find();
            $password = $data['password'] ?: '';
            if ($user) {
                //如果头像为空，则更新头像,更新性别
                $user_data = [];
                if (!$user['avatar'] && $data['avatar']) {
                    $user_data['avatar'] = $data['avatar'];
                }
                if (!$user['gender'] && $data['gender']) {
                    $user_data['gender'] = $data['gender'];
                }
                if (!empty($user_data)) {
                    UserModel::where('id', $user['id'])->update($user_data);
                    $user['avatar'] = $data['avatar'];
                    $user['gender'] = $data['gender'];
                }
                //添加三方信息
                $third_data = [
                    'user_id' => $user['id'],
                    'unionid' => $data['unionid'],
                    'openid' => $data['openid'],
                    'type' => $data['third_type'],
                    'create_time' => time(),
                ];
                $res = Db::name('user_third')->insert($third_data);
                if (!$res) {
                    exception(lang('绑定失败'));
                }
            } else {
                $info['nickname'] = $data['nickname'] ? $data['nickname'] : '';
                $info['gender'] = $data['gender'] ? $data['gender'] : 0;
                $info['avatar'] = $data['avatar'] ? $data['avatar'] : '';
                if ($data['account_type'] == 'account') {
                    $info['account'] = $data['account'];
                }
                if ($data['account_type'] == 'mobile') {
                    $info['mobile'] = $data['account'];
                    $info['account'] = time() . rand(10000, 99999);
                }
                if ($data['account_type'] == 'email') {
                    $info['email'] = $data['account'];
                    $info['account'] = time() . rand(10000, 99999);
                }

                $info['client_id'] = $data['client_id'];
                $info['password'] = '123456a';
                $info['invite_code'] = $data['invite_code'];
                $info['source'] = $data['source'] ? $data['source'] : 2;
                if ($password) {
                    $info['password'] = $password;
                }
                $id = $this->get_reg_data($info);
                if (!$id) {
                    exception(lang('注册失败'));
                }

                //添加三方信息
                $third_data = [
                    'user_id' => $id,
                    'unionid' => $data['unionid'],
                    'openid' => $data['openid'],
                    'type' => $data['third_type'],
                    'create_time' => time(),
                ];
                $res = Db::name('user_third')->insert($third_data);
                if (!$res) {
                    exception(lang('绑定失败'));
                }

                $user = UserModel::where('id', $id)->find();
            }
            //获取会员附加信息
            $user_info = Db::name('user_info')->where('user_id', $id)->find();


            $unset_user = Db::table('lb_user_cancel')->where('user_id', $user['id'])->where('status', 2)->order('aid desc')->find();
            if ($unset_user) {
                return ApiReturn::r(-999, [], lang('此用户已注销'));
            }

            //获取登录需要返回的信息
            $jsonList = $this->get_login_info($user, $user_info);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r($e->getCode(), [], $e->getMessage());
        }
        //TaskModel::doTask($id, 'bindWx');
        return ApiReturn::r(1, ['userinfo' => $jsonList], lang('绑定成功')); //返回给客户端token信息
    }

    /**
     * 生成登录需要的信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/10 14:58
     */
    public function get_login_info($user, $user_info) {
        $routeInfo = request()->routeInfo();
        ///if (empty($routeInfo['var']["version"])) {
        //    return [];
        //}

        $version = $routeInfo['var']["version"];
        // 请求接口的token
        $exp_time1 = 86400 * 365; //token过期时间,这里设置365天
        $scopes1 = 'role_access'; //token标识，请求接口的token
        $access_token = Api::createToken($user, $exp_time1, $scopes1);
        $uuid = Str::uuid();

        //是否开启单点登录,开启后清除该用户现有的token
        $open_single_login = member_config_com('single_login');
        if($open_single_login)
        {
            //获取历史token数据，并清空该token对应的缓存
            $tokens = Db::name('user_token')->where('user_id',$user['id'])->column('uuid');
            foreach ($tokens as $token)
            {
                cache('user_token_'.$version."_". $token, null);
            }
            Db::name('user_token')->where('user_id',$user['id'])->delete();
        }


        cache('userinfo_' . $user['id'].$version, null);
        cache('cache_user_uid_' . $user['id'].'_version_'.$version, null);
        cache('user_token_'.$version."_". $uuid, $access_token);
        // token入表一份
        $token_data = [
            "user_id" => $user["id"],
            "uuid" => $uuid,
            "token" => $access_token,
            "exp_time" => time()+ $exp_time1,
            "login_time" => time(),
            "version" => $version
        ];
        Db::name("user_token")->insert($token_data);

        $user['avatar'] = get_file_url($user['avatar']);
        if (strpos($user['avatar'], 'images/none.png') !== false) {
            $user['avatar'] = config('web_site_domain') . '/static/admin/images/user_none.png';
        }
        //更新登录ip和最后登录时间
        $last_login_ip = $ip = $_SERVER["REMOTE_ADDR"];
        $last_login_time = time();
        Db::table('lb_user')->where('id', $user['id'])->update(['last_login_ip' => $last_login_ip, 'last_login_time' => $last_login_time]);

        //分销商处理开始
        $dis_data = $user;
        $DisFront = new \app\automatic\model\m2979\DisFrant();
        if (!isset($dis_data['lastid'])) {
            $dis_data['lastid'] = Db::table('lb_user')->where('id', $user["id"])->value('lastid');

        }
        if (!isset($dis_data['total_consumption_money'])) {
            $dis_data['total_consumption_money'] = Db::table('lb_user_assets')->where('user_id', $user["id"])->value('total_consumption_money');

        }
        $DisFront::upgrade_dis_info($dis_data, ['once' => 0, 'total' => $dis_data['total_consumption_money']]);
        //分销商处理结束

        $jsonList = [
            'user_token' => $uuid,
            'id' => $user['id'],
            'account' => $user['account'],
            'avatar' => $user['avatar'],
            'real_name' => $user['real_name'],
            'nickname' => $user['nickname'],
            'email' => $user['email'] ?? '',
            'gender' => $user['gender'],
            'mobile' => $user['mobile'] ? preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user['mobile']) : '',
            'birthday' => $user['birthday'],
            'client_id' => $user['client_id'],
            'phone' => $user['mobile']
        ];

        return $jsonList;
    }

    /**
     * 生成登录需要的信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/10 14:58
     */
    public function getLoginInfo($user, $user_info) {
        // 请求接口的token
        $exp_time1 = 86400 * 365; //token过期时间,这里设置365天
        $jsonList = [
            'id' => $user['id'],
            'avatar' => get_file_url($user['avatar']),
            'real_name' => $user['real_name'],
            'nickname' => $user['nickname'],
            'email' => $user['email'] ?? '',
            'gender' => $user['gender'],
            //'user_type' => $user['user_type'],
            'mobile' => $user['mobile'] ? preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user['mobile']) : '',
            'birthday' => $user['birthday'],
            //'address' => $user_info['address'],
            //'address_code' => $user_info['address_code'],
            'client_id' => $user['client_id'],
            //'invite_code' => $user_info['invite_code'],
            //'is_finger' => $user['is_finger'],
            //'autograph' => $user_info['autograph']
            'phone' => $user['mobile'],
            'grassclassify_id' => $user['grassclassify_id'],
            'grassclassifyName_1' => json_decode($user['grassclassifyName_1'],true)
        ];

        return $jsonList;
    }

    /**
     * 获取会员详细信息
     * @param $data .user_id int 会员ID
     * @return \think\response\Json
     * @since 2020年8月28日09:49:52
     * @author zenghu [ 1427305236@qq.com ]
     */
    public function get_user_info($data = [], $user = []) {
        // 获取会员ID
        $user_id = $user['id'];
        $info = UserModel::alias('u')
            ->join('user_info i', 'u.id=i.user_id', 'left')
            ->join('user_assets a', 'u.id=a.user_id', 'left')
            ->field('i.invite_code,i.address,i.address_code,i.hobby,i.tags,i.autograph,i.background')
            ->field('u.id,u.lastid,u.userlevel_id,u.mobile,u.real_name,u.nickname,u.avatar,u.account,u.email,u.birthday,u.gender,u.create_time,u.pay_password,u.grassclassify_id,u.grassclassifyName_1,u.is_companycert')
            ->field("IFNULL(a.user_money, '0.00') as user_money,IFNULL(a.freeze_money, '0.00') as freeze_money,IFNULL(a.total_consumption_money, '0.00') as total_consumption_money,IFNULL(a.score, '0') as score")
            ->where('u.id', $user_id)
            ->find();
        if (!$info) {
            return ApiReturn::r(0, [], lang('请登录'));
        }
        $info['grassclassifyName_1'] = json_decode($info['grassclassifyName_1'],true);
        $info['grassclassifyName_1'] = array_column($info['grassclassifyName_1'],'name');
        // $info['background'] = $info['background']?get_file_url($info['background']):'';
        //$info['phone'] = config("phone");
        //$info['online'] = config("online");
        //校正会员等级错误
        $info['_mobile'] = $info['mobile'];
        $info['mobile'] = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $info['mobile']);
        $info['avatar'] = get_file_url($info['avatar']);
        if (strpos($info['avatar'], 'images/none.png') !== false) {
            $info['avatar'] = config('web_site_domain') . '/static/admin/images/user_none.png';
        }
        $info['userlevel_name'] = Db::name('user_level')->where('aid', $info['userlevel_id'])->value('name');
        $nowTime = time();
        $where = [];
        $where[] = ['status','eq',1];
        $where[] = ['user_id','eq',$user_id];
        $where[] = ['start_time','lt',$nowTime];
        $where[] = ['end_time','gt',$nowTime];
        // $info['coupon'] = Db::name('operation_coupon_record')->where($where)->count();
        $info['coupon'] = 0;
        //$info['age'] = get_age($info['birthday']);
        $info['birthday'] = date('Y-m-d', $info['birthday']);

        $collectionCount = Db::name('user_collection')->alias("uc")
            ->leftjoin('lb_goods goods', 'goods.aid = uc.goods_id')
            ->join("lb_user_merchant um","um.aid=goods.usermerchant_id")
            ->field('IFNULL(count(uc.aid), 0) collectionCount')
            ->where(['uc.user_id' => $user_id])
            ->where('um.status','=',1)
            ->where('um.expiration_time','>',time())
            ->find();
        $info['collection_count'] = $collectionCount['collectionCount'];
        $browseCount = Db::name('user_track')->alias("uc")
            ->leftjoin('lb_goods goods', 'goods.aid = uc.goods_id')
            ->join("lb_user_merchant um","um.aid=goods.usermerchant_id")
            ->field('IFNULL(count(uc.aid), 0) browseCount')
            ->where(['uc.user_id' => $user_id])
            ->where('um.status','=',1)
            ->where('um.expiration_time','>',time())
            ->find();
        $info['browse_count'] = $browseCount['browseCount'];
        $browseCount = Db::name('user_follow')
            ->alias('userfollow')
            ->join('lb_user_merchant usermerchant', 'userfollow.usermerchant_id=usermerchant.aid', 'left')
            ->field('IFNULL(count(userfollow.aid), 0) followCount')
            ->where(['userfollow.user_id' => $user_id])
            ->where('usermerchant.status','=',1)
            ->where('usermerchant.expiration_time','>',time())
            ->find();
        $info['follow_count'] = $browseCount['followCount'];

        // $info['total_money'] = $info['freeze_money'] + $info['withdrawal_money'];
        $info['total_money'] = $info['freeze_money'] + $info['user_money'];
        //会员认证状态 状态-1 未申请 0待审核1已通过2已拒绝
        $info['certified'] = -1;
        $certified = Db::name("user_certified")
            ->where('user_id', $user_id)
            ->find();
        if (!empty($certified)) {
            $info['certified'] = $certified['status'];
        }

        if (!$info['pay_password']) {
            $info['is_pay_password'] = 0;
        } else {
            $info['is_pay_password'] = 1;
        }
        unset($info['pay_password']);

        //分销商处理开始
        $DisFront = new \app\automatic\model\m2979\DisFrant();
        $DisFront::upgrade_dis_info($info, $consume = ['once' => 0, 'total' => $info['total_consumption_money']]);
        $info['distributor_info'] = $DisFront::get_user_disinfo($info['id']);
        //分销商处理结束
        //判断是否开启签到功能
        $is_close = member_config_com('is_close');
        $info['is_close'] = $is_close;

        /*$invite = Db::name('user')
        ->field('id,avatar,nickname')
        ->where('id', $info['lastid'])
        ->find();
        $info['invite'] = $invite;
        if (!empty($invite)) {
            $invite['avatar'] = get_file_url($invite['avatar']);
            $invite['create_time'] = date('Y-m-d', strtotime($info['create_time']));
            $invite['nickname'] = mb_substr($invite['nickname'], 0, 10, 'utf-8');
            $info['invite'] = $invite;
        }*/
        return ApiReturn::r(1, $info, lang('请求成功'));
    }


    /**
     * 会员注册
     * @param array $data
     * @param array $user
     * @return Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/10 15:45
     */
    public function registerUser($data = [], $user = []) {
        // 启动事务
        Db::startTrans();
        try {
            if (empty($data['mobile']) && empty($data['account']) && empty($data['email'])) {
                //
                exception(lang('参数错误'));
            }
            if (!empty($data['mobile'])) {
                //手机号验证码验证
                $logSmsModel = new DySms();
                $result = $logSmsModel->verify_code_m($data['code'], $data['mobile'], $data['type']);
                if (!$result) {
                    exception(lang('手机号或验证码错误'));
                }
            }
            if (!empty($data['email'])) {
                //手机号验证码验证
                $logSmsModel = new EmailSms();
                $result = $logSmsModel->verify_code_m($data['code'], $data['email'], $data['type']);
                // var_dump($result);die;
                if (!$result) {
                    exception(lang('邮箱或验证码错误'));
                }
            }

            $id = $this->get_reg_data($data);
            if (!$id) {
                exception(lang('注册失败'));
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg = $e->getMessage();
            return ApiReturn::r(0, [], $msg);
        }

        $user = UserModel::where('id', $id)->find();
        //获取用户附加信息
        $user_info = Db::name('user_info')->where('user_id', $id)->find();
        // 获取登录需要返回的信息
        $jsonList = $this->get_login_info($user, $user_info);
        //\app\spread\server\Message::sendMsg($id,'lb_user');
        return ApiReturn::r(1, ['userinfo' => $jsonList], lang('注册成功'));
    }

    /**
     * 注册用户信息
     * @param $data
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/10 17:03
     */
    public function get_reg_data($data) {
        //赠送积分设置
        // $register_score = member_config_com("register_score");
        $recommend_register_score = member_config_com("recommend_register_score");

        // 启动事务
        Db::startTrans();
        try {
            $map[] = ['status','=',1];
            $map[] = ['is_del','=',0];

            $res = $this->check_password($data['password']);
            if (!$res) {
                exception('请设置密码为6-32位字母加数字的组合');
            }
            if (!empty($data['mobile'])) {
                $rs = Db::name('user')->where('mobile', $data['mobile'])->where($map)->find();
                if ($rs) {
                    exception(lang('该手机号已注册，请核对'));
                }
            }

            if (!empty($data['account'])) {
                //验证登录账号是否唯一
                $rs = Db::name('user')->where('account', $data['account'])->where($map)->find();
                if ($rs) {
                    exception(lang('登录账号已注册，请核对'));
                }
            }

            if (!empty($data['email'])) {
                $rs = Db::name('user')->where('email', $data['email'])->where($map)->find();
                if ($rs) {
                    exception(lang('该邮箱已注册，请核对'));
                }
            }
            if (isset($data['invite_code']) && $data['invite_code'] != "" && $data['invite_code'] !== 0) {
                $lastid = Db::name('user_info')->where('invite_code', $data['invite_code'])->value('user_id');
                if ($lastid) {
                    $user_data['lastid'] = $lastid;
                }else{
                    exception(lang('邀请码不存在'));
                }
            }
            $user_data['password'] = $data['password'];
            if (!empty($data['mobile'])) {
                $user_data['mobile'] = $data['mobile'];
            }
            if (!empty($data['account'])) {
                $user_data['account'] = $data['account'];
            } else {
                $user_data['account'] = time() . '_' . rand(10000, 99999);
            }
            if (!empty($data['email'])) {
                $user_data['email'] = $data['email'];
            }
            $nickname = lang('用户') . rand(10000, 99999);
            $user_data['real_name'] = $data['real_name'] ?? '';
            $user_data['client_id'] = $data['client_id'];
            $user_data['source'] = (isset($data['source']) && $data['source']) ? $data['source']:1;
            //$user_data['user_type'] = 0;
            //$user_data['user_auth'] = 1;
            $dafault_avatar = config('web_site_domain') . '/static/admin/images/name.png';
            $user_data['avatar'] = $data['avatar'] ? $data['avatar'] : $dafault_avatar;
            $user_data['nickname'] = $data['nickname'] ? $data['nickname'] : $nickname;
            $user_data['create_time'] = time();
            $user_data['status'] = 1;
            $user_data['gender'] = $data['gender'] ? $data['gender'] : 0;
            $user_data['birthday'] = time();
            $userlevel_id = Db::name('user_level')->order('aid asc')->value('aid');
            $user_data['userlevel_id'] = $userlevel_id ? $userlevel_id : 0;
            //配置区号
            $user_data['area_code'] = isset($data['area_code']) ? $data['area_code'] : '86';

            $user_data['user_group'] = "user";
            //注册账号
            $result = UserModel::create($user_data);
            $id = $result->id;
            if (!$id) {
                exception(lang('注册会员失败'));
            }

            $userassets = Db::name('user_assets')->insert([ 'user_id' => $id, 'create_time' => time(), 'update_time' => time()]);
            if (!$userassets) {
                exception(lang('注册资产信息失败'));
            }
            // 新增会员附加信息
            $userInfo = [
                'user_id' => $id,
                'invite_code' => 'IC00' . $id
            ];
            $userinfo = Db::name('user_info')->insert($userInfo);
            if (!$userinfo) {
                exception(lang('注册附加信息失败'));
            }

            //注册赠送积分
            // if($register_score){
            //     //写入积分记录
            //     \app\automatic\model\m2979\ScoreLog::change($id,$register_score, 7);
            // }
            //推荐注册赠送积分
            if($recommend_register_score&&$user_data['lastid']){
                $mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user_data['mobile']);
                //写入积分记录
                \app\automatic\model\m2979\ScoreLog::change($user_data['lastid'],$recommend_register_score, 7,'推荐新用户'.$mobile."注册成功");
            }

            //分销处理

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg = $e->getMessage();
            exception($msg);
        }
        return $id;
    }

    /**
     * 验证码重置密码
     * @param array $data
     * @param array $user
     * @return Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/10 15:45
     */
    public function forgetPassword($data = []) {
        // 启动事务
        Db::startTrans();
        try {
            $map = [];
            switch ($data['account_type']) {
                case 'account':
                    $map['account'] = $data['account'];
                    break;
                case 'mobile':
                    $map['mobile'] = $data['account'];
                    $logSmsModel = new DySms();
                    break;
                case 'email':
                    $map['email'] = $data['account'];
                    $logSmsModel = new EmailSms();
                    break;
                default:
                    return ApiReturn::r(0, [], lang('非法请求'));
                    break;
            }

            //自定义信息，不要定义敏感信息
            $user = Db::table('lb_user')->where($map)->field('id,real_name,nickname,status,avatar,gender,account,user_group,email,mobile,password')->find();
            if (!$user) {
                exception(lang('没有此用户，请注册后登录'), -999);
            }
            if ($data["new_password"]) {
                if ($data["new_password"] != $data['password']) {
                    exception(lang('两次输入密码不一致'));
                }
            }
            if (Hash::check($data['password'], $user['password'])) {
                exception(lang('新密码和原密码一致'));
            }
            if (($data['account_type'] != 'account')  && ($data['code'])) {
                $result = $logSmsModel->verify_code_m($data['code'], $data['account'], $data['type']);
                if (!$result) {
                    exception(lang('验证码错误'));
                }
            }


            $password = Hash::make($data['password']);
            $result1 = Db::table('lb_user')->where('id', $user['id'])->update(['password' => $password]);
            if (!$result1) {
                exception(lang('重置密码失败'));
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $msg = $e->getMessage();
            return ApiReturn::r($e->getCode(), [], $msg);
        }

        return ApiReturn::r(1, [], lang('重置密码成功'));
    }

    /**
     * 旧密码验证修改密码
     * @author 朱龙飞 [ 2420541105 @qq.com ]
     * @created 2019/10/17 0003 14:13
     */
    public function forgetPassword_code($data = [], $user = []) {
        $userinfo_password = UserModel::where('id', $user['id'])->value('password');
        if (isset($data['security_code'])) {
            if (!$userinfo_password) {
                return ApiReturn::r(0, [], lang('您还没有设置密码'));
            }
            $resd = Hash::check($data['security_code'], $userinfo_password); //原密码
            if (!$resd) {
                return ApiReturn::r(0, [], lang('原密码错误'));
            }
        }

        $res = $this->check_password($data['password']);
        if (!$res) {
            return ApiReturn::r(0, [], lang('密码只能是6-32位字母加数字'));
        }
        if ($data['password'] != $data['password_code']) {
            return ApiReturn::r(0, [], lang('新密码和确定密码不一致，请重新输入'));
        }
        $password = Hash::make($data['password']);

        if (Hash::check($data['password'], $userinfo_password)) {
            return ApiReturn::r(0, [], lang('新密码和原密码一致'));
        }
        $result = UserModel::where('id', $user['id'])->update(['password' => $password]);
        if ($result) {
            return ApiReturn::r(1, [], lang('重置密码成功'));
        }
        return ApiReturn::r(0, [], lang('重置密码失败'));
    }

    /**
     * 验证密码
     * @author 朱龙飞 [ 2420541105@qq.com ]
     * @created 2019/9/16 0003 10:57
     */
    public function check_password($password) {
        if (preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$/", $password)) {
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * 校验手机号是否存在
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/8/23 10:16
     */
    public function check_mobile($data = [], $user = []) {
        // 启动事务
        Db::startTrans();
        try {
            $res = UserModel::where(['mobile' => $data['mobile']])->count();
            if ($res) {
                return ApiReturn::r(1, [], lang('手机号存在'));
            }else{
                throw new \Exception(lang('手机号未注册'));
            }

            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, ['userinfo' => ['mobile' => $data['mobile']]], lang('绑定成功'));
    }
    /**
     *验证是否设置登录密码
     */
    public function check_login_password($data=[],$user=[]){
        $login_password = UserModel::where('id', $user['id'])->value('password');
        //如果不传递pay_password，则检查是否设置密码
        if ($login_password) {
            return ApiReturn::r(1, ['falg' => 1], lang('已设置登录密码'));
        }
        return ApiReturn::r(1, ['falg' => 0], lang('未设置登录密码'));
    }

    /**
     * 修改会员个人资料
     * @param string $data
     * @param string $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 杨志刚 [ 1909507511@qq.com ]
     * @since 2019/4/16 15:36
     */
    public function edit_user_info($data = [], $user = []) {
        // error_log(var_export($data,true),3,__FILE__.'$data.log');
        $userId = $user['id'];
        if ($data['birthday']) {
            $birthday = strtotime($data['birthday']);
            if (!$birthday) {
                return ApiReturn::r(0, [], lang('生日格式有误，请重新选择'));
            }
            $data['birthday'] = $birthday;
        }

        if ($data['email'] && $data['email'] != 0) {
            $res = Db::table('lb_user')->where(['email' => $data['email']])->find();
            if ($res && $user['id'] != $res['id']) {
                return ApiReturn::r(0, [], lang('该邮箱已绑定，请核实'));
            }
        }

        $data['update_time'] = time();
        if ($data['avatar'] == "") {
            unset($data['avatar']);
        }
        //修改简介和背景图
        // $user_info_data['background'] = $user_info_data['autograph'] = $data['grassclassifyName_1_id'] = $data['grassclassifyName_1'] = '';
        $user_info_data = [];
        // if($data['background']){
        $user_info_data['background'] = $data['background']??'';
        unset($data['background']);
        // }
        // if($data['autograph']){
        $user_info_data['autograph'] = $data['autograph']??'';
        unset($data['autograph']);
        // }
        //兴趣爱好
        if($data['grassclassify_id']){
            $class_name = Db::name('grass_classify')->where('aid','in',$data['grassclassify_id'])->field('aid,name')->select();
            $data['grassclassifyName_1'] =$data['grassclassifyName_1'] = $class_name?json_encode($class_name):'';
            // $data['grassclassify_id'] =$data['grassclassify_id'];
            $data['grassclassifyName_1_id'] =$data['grassclassify_id']??'';
        }else{
            $data['grassclassifyName_1_id'] = $data['grassclassifyName_1'] = $data['grassclassify_id'] = '';
        }

        unset($data['user_id']);
        // 启动事务
        Db::startTrans();
        try {

            $result = Db::table('lb_user')->where('id', $userId)->update($data);
            if (!$result) {
                throw new \Exception(lang('更新会员信息失败'));
            }
            $data['updatetime'] = $data['update_time'];
            //修改会员附表
            $user_info = Db::table('lb_user_info')->where('user_id', $userId)
                ->find();
            if ($user_info) {
                $res = Db::table('lb_user_info')
                    ->where('user_id', $userId)
                    ->update($user_info_data);
            }

            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }

        $routeInfo = request()->routeInfo();
        $version = $routeInfo['var']["version"];
        cache('userinfo_' . $userId . $version, null);

        $user_data = Db::table('lb_user')->where('id', $userId)->find();
        $user_info = Db::table('lb_user_info')->where('user_id', $userId)->find();
        $jsonList = $this->getLoginInfo($user_data, $user_info);
        return ApiReturn::r(1, ['userinfo' => $jsonList], lang('操作成功'));
    }

    /**
     * 新增或更换绑定的手机号
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/8/23 10:16
     */
    public function bind_mobile($data = [], $user = []) {
        //注意，step=1时，mobile是旧手机号，step=2时，mobile是新手机号
        // 启动事务
        Db::startTrans();
        try {
            $logSmsModel = new DySms();
            if ($data['step'] == 1) {
                $data['mobile'] = Db::name('user')->where('id', $user['id'])->value('mobile');
                if (!preg_match("/^1\d{10}$/", $data['mobile'])) {
                    throw new \Exception(lang('手机号码格式错误'));
                }
            }
            $result = $logSmsModel->verify_code_m($data['code'], $data['mobile'], $data['type']);
            if (!$result) {
                exception(lang('手机号或验证码错误'));
            }

            if ($data['step'] == 1) {
                Db::commit();
                return ApiReturn::r(1, [], lang('验证成功'));
            }

            $res = UserModel::where(['mobile' => $data['mobile']])->count();
            if ($res) {
                throw new \Exception(lang('此手机号已存在，请更换手机号'));
            }

            $res1 = UserModel::where('id', $user['id'])->update(['mobile' => $data['mobile']]);
            if (!$res1) {
                throw new \Exception(lang('绑定失败'));
            }
            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }

        cache('userinfo_' . $user['id'], null);
        return ApiReturn::r(1, ['userinfo' => ['mobile' => $data['mobile']]], lang('绑定成功'));
    }

    /**
     * 更新用户表中用户的设备client_id
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/25 14:18
     */
    public function set_client_id($data, $user) {
        $result = UserModel::where('id', $user['id'])->update(['client_id' => $data['client_id']]);
        if ($result) {
            return ApiReturn::r(1, [], '更新client_id成功');
        }
        return ApiReturn::r(0, [], lang('操作失败'));
    }

    /**
     * 修改会员签名
     * @param string $data .autograph 会员签名
     * @return \think\response\Json
     * @since 2020年8月11日17:05:16
     * @author zenghu [ 1427305236@qq.com ]
     */
    public function edit_user_autograph($data = [], $user = []) {
        // if(!$user){
        //     return ApiReturn::r(1, [], lang('登录状态已失效，请重新登录'));
        // }

        try {
            $data['updatetime'] = time();
            //修改会员附表
            $res = Db::name('user_info')->where('user_id', $user['id'])->update($data);
            if (!$res) {
                throw new \Exception(lang('更新会员附加信息出错'));
            }
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            return ApiReturn::r(0, [], $e->getMessage());
        }
        cache('userinfo_' . $user['id'], null);
        return ApiReturn::r(1, [], lang('操作成功'));
    }


    //设置支付密码
    public function setPayPassword($data = [], $user = []) {
        $password = Hash::make($data['set_pay_password']);
        $result = UserModel::where('id', $user['id'])->update(['pay_password' => $password]);
        if ($result) {
            return ApiReturn::r(1, [], lang('设置支付成功'));
        }
        return ApiReturn::r(0, [], lang('设置支付失败'));
    }

    //判断用户是否设置支付密码
    public function setPayPasswordsten($data = [], $user = []) {
        $result = UserModel::alias('a')
            ->join('user_assets b', 'a.id = b.user_id')
            ->where('a.id', $user['id'])
            ->field('a.id,a.pay_password,b.user_money')
            ->find();
        if ($result['pay_password']) {
            if ($result['user_money'] < $data['pay_money']) {
                return ApiReturn::r(0, [], lang('余额不足'));
            } else {
                return ApiReturn::r(1, [], lang('通过'));
            }
        } else {
            return ApiReturn::r(-1, [], lang('请您设置支付密码'));
        }
    }


    /**
     * Notes: 手机号快捷登录
     * User: chenchen
     * Date: 2021/5/18
     * Time: 15:38
     * @param array $data
     * @param array $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mobile_quick_login($data = [], $user = []) {
        $mobile = $data['mobile'];
        //查询手机号是否注册 如果未注册则自动注册
        $user = UserModel::where(['mobile' => $mobile])->find();
        if (!$user) {
            Db::startTrans();
            try {
                $info['nickname'] = lang('用户') . rand(10000, 99999);
                $info['sex'] = 1;
                $info['password'] = '123456a';
                $info['source'] = 2; //从小程序注册来的
                $info['invite_code'] = $data['invite_code'];
                $info['user_source'] = empty($data['user_source']) ? 'other' : $data['user_source'];
                $id = $this->get_reg_data($info);
                if (!$id) {
                    exception(lang('注册失败'));
                }
                Db::commit();
            } catch (\Exception $e) {
                // 更新失败 回滚事务
                Db::rollback();
                return ApiReturn::r(0, [], $e->getMessage());
            }
            //查询用户信息
            $user = UserModel::where('id', $id)->find();
        } else {
            $id = $user['id'];
        }
        //获取用户附加信息
        $user_info = Db::name('user_info')->where('user_id', $id)->find();
        // 获取登录需要返回的信息
        $jsonList = $this->get_login_info($user, $user_info);
        return ApiReturn::r(1, ['userinfo' => $jsonList], lang('登录成功')); //返回给客户端token信息
    }

    /**
     * 检测支付密码
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function check_pay_password($data = [], $user = []) {
        $pay_password = UserModel::where('id', $user['id'])->value('pay_password');
        //如果传递pay_password，则检查是否正确
        if ($data['pay_password']) {
            //校验旧密码和新密码是否一致

            if (!Hash::check($data['pay_password'], $pay_password)) {
                return ApiReturn::r(0, [], lang('支付密码错误'));
            }
            return ApiReturn::r(1, [], lang('支付密码正确'));
        }

        //如果不传递pay_password，则检查是否设置密码
        if ($pay_password) {
            return ApiReturn::r(1, ['falg' => 1], lang('已设置支付密码'));
        }
        return ApiReturn::r(1, ['falg' => 0], lang('未设置支付密码'));
    }

    /**
     * 修改支付密码
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function update_pay_password($data = [], $user = []) {
        $type = $data['type'] ?? 1;
        $pay_password = UserModel::where('id', $user['id'])->value('pay_password');
        if (Hash::check($data['new_pay_password'], $pay_password)) {
            return ApiReturn::r(0, [], lang('旧密码和新密码一致'));
        }
        if ($type == 1) {
            $resd = Hash::check($data['pay_password'], $pay_password); //原密码
            if (!$resd) {
                return ApiReturn::r(0, [], lang('支付密码输入错误'));
            }
            $result = UserModel::where('id', $user['id'])->update(['pay_password' => Hash::make($data['new_pay_password'])]);
        } else {

            $result = UserModel::where('id', $user['id'])->update(['pay_password' => Hash::make($data['new_pay_password'])]);
        }
        if ($result) {
            return ApiReturn::r(1, [], lang('更新支付密码成功'));
        }
        return ApiReturn::r(0, [], lang('操作失败'));
    }

    /**
     * 校验原支付密码
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function check_old_password($data = [], $user = []) {
        $pay_password = UserModel::where('id', $user['id'])->value('pay_password');
        $resd = Hash::check($data['pay_password'], $pay_password); //原密码
        if (!$resd) {
            return ApiReturn::r(0, [], lang('原密码错误'));
        } else {
            return ApiReturn::r(1, [], 'ok');
        }
    }

    /**
     * 设置支付密码
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function set_pay_password($data = [], $user = []) {
        $password = UserModel::where('id', $user['id'])->value('pay_password');
        if ($password != '') {
            return ApiReturn::r(1, [], lang('密码已存在，请勿重复设置'));
        }

        $info['id'] = $user['id'];
        $data['set_pay_password'] = trim($data['set_pay_password']);
        $info['pay_password'] = Hash::make((string)$data['set_pay_password']);
        $result = UserModel::update($info);
        if ($result) {
            return ApiReturn::r(1, [], lang('设置支付密码成功'));
        }
        return ApiReturn::r(0, [], lang('操作失败'));
    }

    /**
     * 忘记支付密码
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function forget_pay_password($data = [], $user = []) {
        // $LogSms = new DySms();
        $logSmsModel = new DySms();
        $time = time();
        //校验验证码
        // $status = $LogSms->where(['code' => $data['code'], 'phone' => $data['mobile'], 'type' => $data['type']])->where('expiration_time', 'EGT', $time)->value('status');
        // if (!$status) {
        //     return ApiReturn::r(0, [], lang('验证码错误'));
        // }
        $result = $logSmsModel->verify_code_m($data['code'], $data['mobile'], $data['type']);
        if (!$result) {
            exception(lang('手机号或验证码错误'));
        }
        //校验旧密码和新密码是否一致
        $pay_password = UserModel::where('id', $user['id'])->value('pay_password');
        if (Hash::check($data['pay_password'], $pay_password)) {
            return ApiReturn::r(0, [], lang('旧密码和新密码一致'));
        }

        $result = UserModel::where('id', $user['id'])->update(['pay_password' => Hash::make($data['pay_password'])]);
        if ($result) {
            return ApiReturn::r(1, [], lang('支付密码设置成功'));
        }
        return ApiReturn::r(0, [], lang('操作失败'));
    }

    /**
     * 获取用户手机号
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2020/2/15 18:26
     */
    public function get_user_phone($data = [], $user = []) {
        $mobile = UserModel::where(['id' => $user['id']])->value('mobile');
        return ApiReturn::r(1, $mobile, lang('查询成功'));
    }

    /**
     * 修改手机号
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/8/23 10:16
     */
    public function update_mobile($data = [], $user = []) {
        // 启动事务
        Db::startTrans();
        try {
            //校验手机号是否存在
            $res = UserModel::where(['mobile' => $user['mobile']])->count();
            if (!$res) {
                exception(lang('该手机号不存在'));
            }
            //新手机号和原手机号相同
            if ($user['mobile'] == $data['mobile']) {
                exception(lang('新手机号和原手机号相同'));
            }
            //检查新手机号是否已经绑定过
            $check = UserModel::where(['mobile' => $data['mobile']])->find();
            if (isset($check["id"]) && $check["id"] != $user["id"]) {
                exception(lang('该手机号已被绑定'));
            }
            $logSmsModel = new DySms();
            $result = $logSmsModel->verify_code_m($data['code'], $data['mobile'], $data['type']);
            if (!$result) {
                exception(lang('手机号或验证码错误'));
            }
            $res1 = UserModel::where('id', $user['id'])->update(['mobile' => $data['mobile']]);
            if (!$res1) {
                exception(lang('绑定失败'));
            }
            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }

        cache('userinfo_' . $user['id'], null);
        return ApiReturn::r(1, ['userinfo' => ['mobile' => $data['mobile']]], lang('修改手机号成功'));
    }


    /**
     * 校验验证码
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/8/23 10:16
     */
    public function check_verify_code($data = []) {
        if ($data['mobile'] != '') {
            $LogSms = new DySms();
            //校验验证码
            $verify_code = $LogSms->verify_code_m($data['code'], $data['mobile'], $data['type'],0,0);
        } else {
            $EmailSms = new EmailSms();
            //校验验证码
            $verify_code = $EmailSms->verify_code_m($data['code'], $data['user_email'], $data['type'],0,0);
        }

        if (!$verify_code) {
            return ApiReturn::r(0, [], lang('验证码错误'));
        }
        return ApiReturn::r(1, [], lang('验证码正确'));
    }

    /*
     * 保存用户手势密码
     *
     */
    public function hand_password($data = [], $user = []) {
        Db::name("user_info")->where([
            'user_id' => $user['id']
        ])
            ->update([
                'hand_password' => $data['hand_password']
            ]);
        return ApiReturn::r(1, [], 'ok');
    }


    /*
     * 开启关闭指纹支付
     *
     */
    public function finger_payment($data = [], $user = []) {
        //支付密码验证
        if ($data['is_finger'] == 1) {
            $pay_password = UserModel::where(['id' => $user['id']])->value("pay_password");
            $resd = Hash::check($data['pay_password'], $pay_password); //原密码
            if (!$resd) {
                return ApiReturn::r(0, [], lang('支付密码输入错误'));
            }
        }

        UserModel::where(['id' => $user['id']])->update([
            'is_finger' => $data['is_finger']
        ]);
        return ApiReturn::r(1, [], 'ok');
    }


    //获取用户是否设置密码、支付密码
    public function is_password($data = [], $user = []) {
        $passwordInfo = Db::name('user')->where(['id' => $user['id']])->field('password,pay_password')->find();
        $result['is_password'] = $passwordInfo['password'] ? 1 : 0;
        $result['is_pay_password'] = $passwordInfo['pay_password'] ? 1 : 0;
        return ApiReturn::r(1, $result, 'ok');
    }
    //原 useraddons
    /**
     * 会员签到
     * @param array $data
     * @param array $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/11 16:51
     */
    public function userSignin($data = [], $user = []) {
        //实例化签到模型
        $sign = new \app\userbase\model\Signin();
        $result = $sign->userSignin($user['id'], $data['type']);
        if (false === $result) {
            return ApiReturn::r(0, [], $sign->getError());
        }

        //签到成功
        if ($result['status'] == 1) {
            TaskModel::doTask($user['id'], 'firstSign');
            return ApiReturn::r(1, $this->filter($result, $this->fname), $result["msg"] . "," .lang('已连续签到') . $result['days'] . lang('天'));
        }
        //重复签到
        if ($result['status'] == 2) {
            return ApiReturn::r(1, $this->filter($result, $this->fname), $result['msg']);
        }
    }

    /**
     * 获取签到信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/11 16:35
     */
    public function get_user_signin($data = [], $user = []) {
        $sign = new \app\userbase\model\Signin();
        //获取今日签到数据
        $todayData = $sign->todayData($user['id']);
        if (false === $todayData) {
            return ApiReturn::r(0, [], $sign->getError());
        }
        $result = $sign->getInsertData($user['id']);
        if ($todayData['is_sign'] == 0) {
            $result['days'] = $result['days'] - 1; //因为是组装的数据，如果没签到的话，就-1
        }
        $result['today'] = $todayData['is_sign'] ? $todayData['is_sign'] : 0;
        $result['score'] = \app\userbase\model\User::where('id', $user['id'])->value('score');
        $result['sign_total'] = $sign::where(['user_id' => $user['id']])->count();
        //$result = $this->filter($result, $this->fname);
        $sign_rule = \app\userbase\model\SigninRule::where(1)->order("day asc")->select();

        $sign_day = [];
        foreach ($sign_rule as $v) {
            $st = date('Y-m-d', strtotime('Sunday ' . ($v["day"] - 7) . ' day'));
            $res = Db::name('user_signin')
                ->where(['user_id' => $user['id']])
                ->whereTime('create_time', 'between', [$st . ' 00:00:00', $st . ' 23:59:59'])
                ->find();
            $sign_day[] = ['day' => $v["day"],'integral' => $v["integral"],'coupon_id' => $v["coupon_id"],'text' => $v["integral"] . '积分' . ($v["coupon_id"] ? '+优惠券' :''),'is_sign' => ($res ? 1 : 0)];
        }
        $result['week_sign_info'] = $sign_day;
        $y = "";
        $m = "";
        $start_time = $data['start_time'] ?? '';
        if ($start_time) {
            $y = explode("-", $start_time)[0];
            $m = explode("-", $start_time)[1];
        }
        $now_month = $this->mFristAndLast($y, $m);
        $result2 = $sign::where(['user_id' => $user['id']])->whereTime('create_time', 'between', [$now_month['firstday'], $now_month['lastday']])->order("create_time desc")->paginate();
        $result = $result + $result2->toArray();
        foreach ($result['data'] as &$value) {
            $value['create_time'] = date("Y-m-d", strtotime($value['create_time']));
        }
        $result["user_signin_rule"] = Db::name("user_signin_rule")->select();
        return ApiReturn::r(1, $result, lang('请求成功'));
    }


    //获取当月的开始时间和结束时间
    public function mFristAndLast($y = "", $m = "") {
        if ($y == "") {
            $y = date("Y");
        }
        if ($m == "") {
            $m = date("m");
        }
        $m = sprintf("%02d", intval($m));
        $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);
        $m > 12 || $m < 1 ? $m = 1 : $m = $m;
        $firstday = strtotime($y . $m . "01000000");
        $firstdaystr = date("Y-m-01", $firstday);
        $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

        return array(
            "firstday" => $firstday,
            "lastday" => $lastday
        );
    }

    /**
     * 会员实名认证
     * @param array $data
     * @param array $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/1 19:36
     */
    public function certification($data = [], $user = []) {
        // 启动事务
        Db::startTrans();
        try {
            $data['user_id'] = $user['id'];
            // 验证
            $result = $this->validate($data, 'userbase/Certified.add');
            if (true !== $result) {
                exception($result);
            }
            //同一个用户，每种认证类型，只能有一条记录
            if ($data['is_reset']) {
                //如果是重新提交，则保存资料
                $data['update_time'] = time();
                $data['status'] = 0; //待审核
                $res = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->update($data);
                if (!$res) {
                    exception(lang('提交认证材料失败'));
                }
            } else {
                $userCertified = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->find();
                if ($userCertified && $userCertified['status'] != 2) {
                    exception(lang('认证中，请勿重复提交'));
                } else {
                    if ($userCertified['user_id']) {
                        $data['status'] = 0; // 认证失败重新提交状态为待审核
                        $res = Certified::where(['user_id' => $user['id'], 'auth_type' => $data['auth_type']])->update($data);
                    } else {
                        $res = Certified::create($data);
                    }
                    if (!$res) {
                        exception(lang('提交认证材料失败'));
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }

        return ApiReturn::r(1, [], lang('提交成功'));
    }

    /**
     * 获取认证状态
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/1 20:22
     */
    public function certification_status($data = [], $user = []) {
        $res = Certified::where('user_id', $user['id'])->find();
        if ($res) {
            $result = $this->filter($res, $this->fname);
            return ApiReturn::r(1, $result, lang('请求成功'));
        } else {
            return ApiReturn::r(1, ['status' => 99], lang('未认证'));
        }
    }

    /**
     * 获取积分明细
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/9 10:38
     */
    public function get_score_list($data = [], $user = []) {
        $data['type'] = $data['type'] ?? 0;
        $data['start_time'] = $data['start_time'] ?? "";
        $data['end_time'] = $data['end_time'] ?? "";
        $data['user_id'] = $user['id'];
        $result = \app\userbase\model\ScoreLog::getList($data);

        if ($result) {
            return ApiReturn::r(1, $result, lang('请求成功'));
        } else {
            return ApiReturn::r(1, [], lang('暂无数据'));
        }
    }


    /**
     * 关注/取关
     * @param $data
     * @param $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/9 13:55
     */
    public function follow($data = [], $user = []) {
        $follow = new \app\userbase\model\Follow();
        $user_id = $data['user_id']; //被关注人ID
        $fans_id = $user['id']; //我的ID
        if ($user_id == $fans_id) {
            return ApiReturn::r(0, '', lang('你不能自己关注自己'));
        }
        $res = $follow->isFollow($user_id, $fans_id);
        if ($res) {
            $ret = $follow->delFollow($user_id, $fans_id);
            if ($ret) {
                return ApiReturn::r(1, ['follow' => 0], lang('取消关注成功'));
            }
        } else {
            $ret = $follow->saveFollow($user_id, $fans_id);
            if ($ret) {
                return ApiReturn::r(1, ['follow' => 1], lang('关注成功'));
            }
        }
        return ApiReturn::r(0, [], lang('关注失败'));
    }

    /**
     *
     * 关注 和 粉丝列表
     * @param  $data
     * @param  $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhulongfei [ 242054105@qq.com ]
     * autograph  nickname avatar
     *
     */
    public function follow_attention($data = [], $user = []) {
        $type = $data["type"];
        //我的关注
        if ($type == 1) {
            $uid = $user['id'];
            $res = Db::name("user_follow")
                ->alias("f")
                ->field("f.id,u.avatar,u.nickname,f.create_time,f.fans_id,f.user_id,ui.autograph")
                ->join("user u", "f.user_id = u.id")
                ->join("user_info ui", "ui.user_id = u.id")
                ->where("f.fans_id", $uid)
                ->order("f.create_time desc")
                ->paginate()
                ->each(function ($item, $key) {
                    $item['is_follow'] = 1;
                    $item['avatar'] = get_file_url($item['avatar']);
                    return $item;
                });
        } elseif ($type == 2) {
            //我的粉丝
            $res = Db::name("user_follow")
                ->alias("f")
                ->field("f.id,u.avatar,u.nickname,f.create_time,f.fans_id,f.user_id,ui.autograph")
                ->join("user u", "f.fans_id = u.id")
                ->join("user_info ui", "ui.user_id = u.id")
                ->where("f.user_id", $user['id'])
                ->order("f.create_time desc")
                ->paginate()
                ->each(function ($item, $key) {
                    $item['is_follow'] = \think\Db::name('user_follow')->where(['user_id' => $item['fans_id'], 'fans_id' => $item['user_id']])->count();
                    $item['avatar'] = get_file_url($item['avatar']);
                    return $item;
                });
        }
        if ($res) {
            return ApiReturn::r(1, $res, lang('请求成功'));
        }
        return ApiReturn::r(1, [], lang('没有更多数据了'));
    }
    /**
     * 手动绑定关系
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/29 11:20
     */
    public function set_user_lastid($data = [], $user = []) {
        //先查询是否有推荐人
        $now_lastid = Db::name('user')->where('id', $user['id'])->value('lastid');
        if ($now_lastid) {
            return ApiReturn::r(0, [], lang('您已经有推荐人了，请勿重复绑定'));
        }
        //查询邀请码所属的用户id
        $lastid = Db::name('user_info')->where('invite_code', $data['invite_code'])->value('user_id');
        if ($lastid) {
            $res = Db::name('user')->where('id', $user['id'])->update(['lastid' => $lastid]);
            if ($res) {
                return ApiReturn::r(1, [], lang('绑定成功'));
            }
        } else {
            return ApiReturn::r(0, [], lang('未找到推荐人信息'));
        }
        return ApiReturn::r(0, [], lang('绑定失败'));
    }
    /**
     * cancel_account
     * ${FILE_NAME}
     *
     * current file name
     * Administrator：zlf  242054110@qq.com
     * 日期：2021/9/13
     * 时间：16:01
     * 项目名称：taizhou
     */
    public function cancel_account_type($data, $user) {
        $user_cancel_account = Db::name("user_unsubscribe_cause")->where([
            "status" => 1
        ])->select();
        if ($user_cancel_account) {
            return ApiReturn::r(1, $user_cancel_account, lang('成功'));
        } else {
            return ApiReturn::r(0, [], lang('失败'));
        }

    }

    //提交注销账户申请
    public function do_unset($data = [], $user = []) {
        // $param['name'] = $data['reason'];
        // $param['userunsubscribecause_id'] = $data['aid'];
        // $user_cancel_account = Db::name("user_unsubscribe_cause")->where([
        //     "name" => $param['name']
        // ])->find();
        $data['reason'] = $data['reason'] ?? '';
        $param['create_time'] = time();
        $check = Db::name("user_unset")->where("user_id", $user["id"])->find();
        if ($check) {
            Db::name("user_unset")->where("user_id", $user["id"])->update([
                "mobile" => $user["mobile"],
                "create_time" => time(),
                "userunsubscribecause_id" => $data['aid'],
                "status" => 0,
                'reason' => $data['reason']
            ]);
        } else {
            Db::name("user_unset")->insert([
                "user_id" => $user["id"],
                "mobile" => $user["mobile"],
                "create_time" => time(),
                "userunsubscribecause_id" => $data['aid'],
                "status" => 0,
                'reason' => $data['reason']
            ]);
        }
        return ApiReturn::r(1, [], '请求成功');
    }

    //获取注销账户申请状态
    public function get_unset($data = [], $user = []) {
        $check = Db::name("user_unset")->where("user_id", $user["id"])->order('id desc')->find();
        $status = $check ? $check["status"] : -1;
        // if($status == 2){
        //     $status = -1;
        // }
        // $cancellation_reason = $check['name'];
        // $rule = \app\userbase\model\ArticleColumn::where("aid",7)->value("content");
        $cancellation_reason = Db::table('lb_user_unsubscribe_cause')->where('aid', $check['userunsubscribecause_id'])->alias('unsubscribe_cause')->value('unsubscribe_cause.name');
        $cancellation_reason = $cancellation_reason ? $cancellation_reason  : $check['reason'];
        $rule = Db::table('lb_operation_article')->where('aid', 8)->alias('operationarticle')->value('operationarticle.content');
        // dump($rule);die;
        return ApiReturn::r(1, ["status" => $status, "rule" => $rule, 'cancellation_reason' => $cancellation_reason], '请求成功');
    }
    /**
     * 会员等级 及升级所需的条件
     */
    public function get_level_info($data = [], $user = []) {
        $user_info = Db::name("user")->where("id", $user["id"])->field("id,total_consumption_money,avatar,nickname,userlevel_id,user_type")->find();
        $level_info = Db::name("user_level")->where("aid", $user_info["userlevel_id"])->find();

        $rule = \app\userbase\model\ArticleColumn::where("id", 10)->value("content");
        $user_info["name"] = $level_info["name"];
        return ApiReturn::r(1, ["user_info" => $user_info, "level_info" => $level_info, "rule" => $rule], '请求成功');
    }



    /**
     * 获取全国城市信息
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/23 17:39
     */
    public function getCity($data = []) {
        $where = ['pid' => ($data['pid']?$data['pid']:0)];
        $area = Db::name('china_area')->where($where)->select();
        return ApiReturn::r(1, ['list' => $area], '操作成功');
    }

    /**
     * Notes: 获取国际手机区号
     * User: chenchen
     * Date: 2021/5/22
     * Time: 14:56
     * @param array $data
     * @param array $user
     */
    public function area_code($data = [], $user = []) {
        $list = Db::name("phone_prefix")->select();
        $res = [];
        foreach ($list as $v) {
            $res[$v['letter']][] = [
                'country' => $v["country"] . ' +' . $v["prefix"],
                'prefix' => $v["prefix"]
            ];
        }
        if (!empty($res)) {
            ksort($res);
        }
        return ApiReturn::r(1, $res, 'ok');
    }

    /**
     * 获取指定广告位的广告列表
     * @param array $data 参数
     * @param array $user
     * @return json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function get_ads($data = [], $user = []) {
        $result = AdsModel::where(['typeid' => $data['typeid'], 'status' => 1])->order('sort asc,id desc')->select();
        foreach ($result as &$v) {
            if ($v['thumb']) {
                $v['thumb'] = get_file_url($v['thumb']);
            }
            if ($v['video']) {
                $v['video'] = get_file_url($v['video']);
            }
            if ($data['typeid'] == 2) {
                $v['rgb'] = json_decode($v['rgb']);
            }
            //                halt($this->fname);
            //                $v = $this->filter($v, $this->fname);
        }
        return ApiReturn::r(1, $result, lang('请求成功'));


    }

    public function img($img) {
        $rTotal = 0;
        $gTotal = 0;
        $bTotal = 0;
        $total = 0;
        $i = imagecreatefrompng($img);
        if (!$i) {
            $i = imagecreatefromjpeg($img);
        }
        for ($x = 0; $x < imagesx($i); $x++) {
            for ($y = 0; $y < imagesy($i); $y++) {
                $rgb = imagecolorat($i, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;
                $rTotal += $r;
                $gTotal += $g;
                $bTotal += $b;
                $total++;
            }
        }
        if ($total == 0) {
            $rAverage = 0;
            $gAverage = 0;
            $bAverage = 0;
        } else {
            $rAverage = round($rTotal / $total);
            $gAverage = round($gTotal / $total);
            $bAverage = round($bTotal / $total);
        }

        return [$rAverage,$gAverage,$bAverage];
    }

    /**
     * Notes:获取广告位详情，主要用于PV统计
     * User: php迷途小书童
     * Date: 2020/8/24
     * Time: 17:43
     * @param array $data
     * @param array $user
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_ads_detail($data = [], $user = []) {


        return ApiReturn::r(1, [], lang('记录成功'));
    }

    /**
     * 获取指定导航位的导航列表
     * @param string $data 参数
     * @return json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function get_nav($data = '') {
        $result = NavModel::where(['typeid' => $data['typeid'], 'status' => 1])
            ->order('sort asc')
            ->select();
        foreach ($result as &$v) {
            if ($v['thumb']) {
                $v['thumb'] = get_file_url($v['thumb']);
            }
            $v = $this->filter($v, $this->fname);
        }
        return ApiReturn::r(1, $result, lang('请求成功'));
    }



    //获取验证码
    /**
     * 获取验证码
     * @param array $data 参数
     * @return json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function get_code($data = [], $user = []) {

        if ($data['mobile']) {
            if (!preg_match("/^1\d{10}$/", $data['mobile']) && $data['type'] != 4 && $data['mobile'] != '') {
                return ApiReturn::r(0, [], lang('请输入正确的手机号格式'));
            }
            $field = 'mobile';
            $value = $data['mobile'];
        } else {
            if (!preg_match("/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i", $data['user_email']) && $data['user_email'] != '') {
                return ApiReturn::r(0, [], lang('请输入正确的邮箱格式'));
            }
            $field = 'email';
            $value = $data['user_email'];
        }
        switch ($data['type']) {
            case 1:// 注册
                $userInfo = Db::table('lb_user')->where($field, $value)
                    ->find();
                if ($userInfo) {
                    if ($userInfo['status'] == 0 || $userInfo['is_del'] == 1) {
                        return ApiReturn::r(0, [], lang('此用户被禁用，请联系客服咨询'));
                    } else {
                        return ApiReturn::r(0, [], lang('账号信息已存在，无法注册'));
                    }
                }
                break;
            case 2:// 忘记密码
                $userInfo = Db::table('lb_user')
                    ->where($field, $value)->find();
                if (!$userInfo) {
                    return ApiReturn::r(0, [], lang('账号不存在'));
                }
                if ($userInfo['is_del'] == 1 || $userInfo['status'] != 1) {
                    return ApiReturn::r(0, [], lang('此用户被禁用，请联系客服咨询'));
                }
                break;
            case 3:// 短信登录
                //如果开启一键登录注册的话，注释掉
                $userInfo = Db::name('user')
                    ->where($field, $value)->find();
                if ($userInfo && ($userInfo['is_del'] == 1 || $userInfo['status'] == 0)) {
                    return ApiReturn::r(0, [], lang('此用户被禁用，请联系客服咨询'));
                }
                break;
            case 4: //修改手机号
                $user = \app\common\model\Api::get_user_info();
                if (!$user['id']) {
                    return ApiReturn::r(0, [], lang('旧账号获取失败'));
                }
                // $data['mobile'] = \think\Db::name('user')->where('id', $user['id'])->value('mobile');
                // if (!preg_match("/^1\d{10}$/", $data['mobile'])) {
                //     return ApiReturn::r(0, [], lang('手机号错误'));
                // }
                break;
            case 5:// 绑定手机号
                //新手机号和原手机号相同
                if ($user[$field] == $value) {
                    return ApiReturn::r(0, [], lang('新账号和原账号相同'));
                }
                //检查新手机号是否已经绑定过
                $check = \app\user\model\User::where([$field => $value])
                    ->find();
                if (isset($check["id"]) && $check["id"] != $user["id"]) {
                    return ApiReturn::r(0, [], lang('该账号已被绑定'));
                }
                $userInfo = Db::name('user')->where($field, $value)->find();


                break;
            case 6:
                $mobile_count = Db::name('user')->where($field, $value)->count();
                if (!$mobile_count) {
                    return ApiReturn::r(0, [], lang('账号不存在'));
                }
                break;
            default:
                break;

        }

        $isTest = $data['is_test'] == 1 ? true : false;
        $phoneVerify = rand(1000, 9999);
        try {
            $type = $data['type'] ? $data['type'] : 0;
            if ($data['mobile']) {
                /*$expiration_time = LogSms::where(['phone'=>$data['mobile'],'type'=>$type])->order('aid DESC')->value('expiration_time');
                if(time() <= $expiration_time){
                  return ApiReturn::r(0, [], '验证码五分钟有效，请勿重复发送！');
                }*/

                //$logSmsModel = new LogSms();
                //阿里短信
                //$logSmsModel->sendDysms1($phoneVerify, $data['mobile'], $type, $isTest);
                //互亿短信
                //$logSmsModel->sendHuyi($phoneVerify, $data['mobile'], $type,$isTest);
                //掌榕短信
                if(!$isTest)
                {
                    $version = input('version');
                    $member_id = str_replace('m','',$version);
                    $model = new SmsZrwService();
                    $res = $model->deploy_send($member_id, $data['mobile'], $phoneVerify);
                    if ($res["code"] == 0) {
                        exception(lang($res["msg"]));
                    }
                }
                $expiration = 5;
                $content = '您的短信验证码为：' . $phoneVerify . ',有效期为' . $expiration . '分钟';

                $res = (new LogSms())->add_sms($phoneVerify, $data['mobile'], $type, $content, "zhangrong", $expiration);
            } else {
                $expiration = 5;
                $content = '您的验证码为：' . $phoneVerify . ',有效期为' . $expiration . '分钟';
                $emailConfig = \app\member\model\MemberConfig::getMemberConfig(MemberID, "email");
                $EmailSmsModel = new EmailSend($emailConfig);
                //发送邮箱验证码
                $EmailSmsModel->sendEmail($data['user_email'], "邮箱验证码", $content, $emailConfig["type"]);
                (new LogSms())->add_sms($phoneVerify, $data["user_email"], $type, $content, "email", $expiration);
            }
        } catch (\Exception $e) {
            //$e->getMessage()
            return ApiReturn::r(0, [], lang('验证码发送失败') . ':' . $e->getMessage());
        }
        $params = [
            'index' => 'search_84',
            'body' => [
                'mappings' => [
                    'properties' => [
                        'question' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word'
                        ],
                    ],
                ],
            ],
        ];
        $params = [ 'index' => 'search_84', 'body' => [ 'mappings' => [ 'properties' => [ 'question' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', ], ], ], ], ]; $result = $client->indices()->create($params);
        $params = [ 'index' => 'search_84', 'body' => [ 'mappings' => [ 'properties' => [ 'question' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', ], ], ], ], ];

        if ($isTest) {
            return ApiReturn::r(1, ['code' => $phoneVerify], lang('发送成功'));
        }
        return ApiReturn::r(1, [], lang('发送成功'));
    }

    //余额开始
    /**
     * 我的余额
     * @return void
     * @since 2019/4/23 18:21
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function get_my_money20220812($data = [], $user = []) {
        $money = Db::name('user_assets')
            ->field('user_id,user_money,freeze_money')
            ->where('user_id', $user['id'])
            ->find();
        $money['min_withdraw_money'] = module_config('user.min_withdraw_money');
        $money['withdraw_handling_type'] = module_config('user.withdraw_handling_type');
        $money['withdraw_handling_fee'] = module_config('user.withdraw_handling_fee');
        $money['total_revenue_money'] = bcadd($money['user_money'], $money['freeze_money'], 2); //用户总金额=用户余额+冻结金额
        $money['freeze_money_rule'] = module_config('user.freeze_money_rule'); //冻结金额规则显示
        //分享赚-暂时屏蔽
        $money['share_money'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => 8
        ])->sum("change_money");
        //自购返-暂时屏蔽
        $money['discounts_money'] = 0;
        //可提现余额
        $money['money'] = $money['user_money'];

        return ApiReturn::r(1, $money, lang('请求成功'));
    }
    public function get_my_money($data = [], $user = []) {
        $money = Db::table('lb_user')
            ->field('id,user_money,freeze_money')
            ->where('id', $user['id'])
            ->find();
        //冻结金额为提现审核中的金额
        $cold_money = Db::table('lb_user_withdraw')->where('user_id', $user['id'])->where('check_status', 0)->where('cash_status', 0)->sum('cash_fee');
        $money['min_withdraw_money'] = member_config_qiye('min_withdraw_money');
        $money['withdraw_handling_type'] = member_config_qiye('withdraw_handling_type') ?? 1;
        $money['withdraw_handling_fee'] = member_config_qiye('withdraw_handling_fee');
        $money['total_revenue_money'] = bcadd($money['user_money'], $cold_money, 2); //用户总金额=用户余额+冻结金额
        $money['freeze_money_rule'] = member_config_qiye('freeze_money_rule'); //冻结金额规则显示
        //分享赚-暂时屏蔽
        $money['share_money'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => 8
        ])->sum("change_money");
        //自购返-暂时屏蔽
        $money['discounts_money'] = 0;
        //可提现余额
        $money['money'] = $money['user_money'];

        return ApiReturn::r(1, $money, lang('请求成功'));
    }
    public function get_zi_money($data = [], $user = []) {
        $change_type = input("change_type");
        //        $money = \think\Db::name('user')->where('id', $user['id'])->find();
        //        $money['min_withdraw_money'] = $this->module_config('user.min_withdraw_money');
        //        $money['withdraw_handling_type'] = $this->module_config('user.withdraw_handling_type');
        //        $money['withdraw_handling_fee'] = $this->module_config('user.withdraw_handling_fee');
        //        $money['total_revenue_money'] = bcadd($money['user_money'], $money['freeze_money'], 2);   //用户总金额=用户余额+冻结金额
        //        $money['freeze_money_rule'] = $this->module_config('user.freeze_money_rule');  //冻结金额规则显示
        //分享赚-暂时屏蔽
        $money['today'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => $change_type
        ])->whereTime('create_time', 'today')->sum("change_money");
        $money['week'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => $change_type
        ])->whereTime('create_time', 'week')->sum("change_money");
        $money['month'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => $change_type
        ])->whereTime('create_time', 'month')->sum("change_money");
        $money['last_month'] = Db::name("user_money_log")->where([
            'user_id' => $user['id'],
            'change_type' => $change_type
        ])->whereTime('create_time', 'last month')->sum("change_money");
        $money['list'] = ["data" => [1,2,3,4,5,6,7],"categories" => [1,2,3,4,5,6,7]];
        //自购返-暂时屏蔽
        //        $money['discounts_money'] = 0;
        //        //可提现余额
        //        $money['money'] = $money['user_money'];

        return ApiReturn::r(1, $money, lang('请求成功'));
    }


    //冻结列表
    public function cold_list($data = [], $user = []) {
        $where = [];
        $where[] = ['user_id','=',$user['id']];
        $where[] = ['is_del','=',0];
        // $where[] = ['status', 'in', [1, 2, 3]];

        // if ($data['start_time'] && $data['end_time']){
        //     $where[] = ['create_time','between time',[strtotime($data['start_time']),strtotime($data['end_time'] . " 23:59:59")]];
        // }

        $order = "aid desc";

        // dump($where);die;
        $dataList = Db::table('lb_distributor_award')
            ->field('aid, status, detail_bonus , create_time, order_sn,is_settle')
            ->where($where)
            ->order($order)
            ->paginate()->each(function ($infodataList) {
                $infodataList['create_time'] = $infodataList['create_time']? date('Y-m-d H:i:s', $infodataList['create_time']) : '';
                $infodataList['is_settle'] = $infodataList['is_settle'] == 0 ? '冻结中' : '已解冻';
                return $infodataList;
            });
        $count = Db::table('lb_distributor_award')
            ->field('aid, status, detail_bonus , create_time, order_sn,is_settle')
            ->where($where)
            ->count();
        $res = [
            'count' => $count,
            'list' => $dataList
        ];
        return ApiReturn::r(1, $res, "请求成功");
    }


    /**
     * 获取余额交易明细
     * @return void
     * @throws DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @since 2019/4/23 18:30
     */
    public function get_money_detail($data = [], $user = []) {
        $change_type = $data['change_type'] ? intval($data['change_type']) : 0;
        $where = [];
        if ($data['date']) {
            $start_time = strtotime($data['date']);
            $end_time = strtotime('+1 month', $start_time);
            $where[] = ["create_time","BETWEEN",[$start_time,$end_time]];
        }
        if ($data['start_data'] && $data['end_data']) {
            $start_time = strtotime($data['start_data']);
            $end_time = strtotime($data['end_data'] . " 23:59:59");
            $where[] = ["create_time","BETWEEN",[$start_time,$end_time]];
        }

        if ($change_type) {
            switch ($change_type) {
                //充值记录
                case 1:
                    $where[] = ['change_type','in','1,3'];
                    $where[] = ["change_money",">",0];
                    break;
                //消费明细
                case 2:
                    $where[] = ['change_type','in','2,4,5,6,7,8,9,10'];
                    $where[] = ["change_money","<",0];
                    break;
                //收入记录
                case 3:
                    $where[] = ["change_money",">",0];
                    break;
                //支出记录
                case 4:
                    $where[] = ["change_money","<",0];
                    break;
                default:
                    break;
            }
        }
        $lists = MoneyLog::where($where)
            ->where('user_id', $user['id'])
            ->where($where)
            ->order('aid', 'desc')
            ->paginate()
            ->each(function ($item) {
                $item['check_reason'] = '';
                if (floatval($item['change_money']) > 0) {
                    $item['t'] = 1;
                } else {
                    $item['t'] = 2;
                }
                return $item;
            });
        return ApiReturn::r(1,$lists,lang('请求成功'));
    }

    /**
     * 上传微信或支付宝提现账号信息
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/13 20:46
     */
    public function bind_withdraw_account($data,$user) {
        $data['user_id'] = $user['id'];
        $WithdrawAccount = new \app\userbase\model\WithdrawAccount();
        $info = $WithdrawAccount->where(['user_id' => $user['id'],'account_type' => $data['account_type']])->find();
        // 启动事务
        Db::startTrans();
        try {
            if (empty($data['account_id'])) {
                exception(lang('绑定账号不能为空'));
            }
            if ($info) {
                $res1 = $WithdrawAccount->where(['user_id' => $user['id']])->update(['is_default' => 0, 'update_time' => time()]);
                $data['update_time'] = time();
                $res = $WithdrawAccount->where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->update($data);
                if ($res === false || $res1 == false) {
                    exception(lang('绑定失败'));
                }
            } else {
                $data['status'] = 1;
                $res = $WithdrawAccount->create($data);
                if (!$res) {
                    exception(lang('绑定失败'));
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        $info = $WithdrawAccount->where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->find();
        return ApiReturn::r(1, $info, lang('绑定成功'));
    }

    /**
     * 获取绑定的提现账号
     * @param $data
     * @param $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/13 21:39
     */
    public function get_withdraw_account($data, $user) {
        $res = WithdrawAccount::where(['user_id' => $user['id'], 'account_type' => $data['account_type']])->find();

        if ($res) {
            if ($res['status'] == 1) {
                if ($data['account_type'] != 3 && $res['qrcode'] == '') {
                    return ApiReturn::r(0, [], lang('暂未绑定'));
                }
            } else {
                return ApiReturn::r(0, [], lang('暂未绑定'));
            }
        } else {
            return ApiReturn::r(0, [], lang('暂未绑定'));
        }
        $res['qrcode_url'] = get_file_url($res['qrcode']);
        //        $result = $this->filter($res, $this->fname);
        return ApiReturn::r(1, $res, lang('请求成功'));
    }

    /**
     * 申请提现
     * @return Json
     * @since 2019/4/23 19:05
     * @editor 李志豪 [ 995562569@qq.com ]
     * @updated 2019.05.21
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function withdraw($data = [], $user = []) {

        $money = $data['money'];
        $type = $data['type'];
        // $userInfo = User::get($user['id']);
        $userInfo = Db::table('lb_user')->where('id', $user['id'])->find();
        if (empty($userInfo['pay_password'])) {
            return ApiReturn::r(1001, [], lang('请设置支付密码'));
        }
        $_type = 2;
        $time = strtotime(date("Y-m-d"));
        $_where[] = ['user_id','=',$user['id']];
        $_where[] = ['time','gt',$time];
        $_where[] = ['type','=',$_type];

        $count = Db::name('user_login_info')->where($_where)->count();
        if (!Hash::check($data['pay_password'], $userInfo['pay_password'])) {
            $now_time = time();
            Db::name('user_login_info')->insert([
                'mobile' => $user['mobile'],
                'create_time' => $now_time,
                'user_id' => $user['id'],
                'type' => $_type
            ]);
            if ($count >= $this->module_config("user.pay_count")) {
                return ApiReturn::r(0, [], '账号支付密码已被锁定,请明天再试');
            } else {
                return ApiReturn::r(1002, [], lang('支付密码错误'));
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            //申请
            // WithdrawModel::addInfo($userInfo, $money, $type);


            // 读取实时金额
            $now_money = Db::table('lb_user')->where('id', $user['id'])->lock(true)->value('user_money');
            $wd_min_money = member_config_qiye('min_withdraw_money');

            // 提现金额起提标准判断
            if ($now_money < $wd_min_money) {
                return ApiReturn::r(0, [], lang('您的余额暂未达到提现标准'));
            }

            // 提现金额最低标准判断
            if ($wd_min_money > $money) {
                exception(lang('提现金额最低为') . $wd_min_money . lang('元'));
            }

            // 提现金额不能大于余额
            if ($money > $now_money) {
                exception('余额不足，无法提现');
            }
            //提现余额为减法
            $tx_money = -$money;

            $order_no = get_order_sn('TX');
            // 变更余额记录
            $moneylog = $this->changeMoney($user['id'], $now_money, $tx_money, 4, $remark = lang('会员申请提现'), $order_no);
            if (!$moneylog) {
                exception(lang('更改余额失败'));
            }

            //组合用户提现信息
            $account = Db::table('lb_user_withdraw_account')->where(['user_id' => $user['id'], 'account_type' => $type])->field('id,true_name')->find();
            $withdraw_data = [
                'user_id' => $user['id'],
                'true_name' => $account['true_name'],
                'order_no' => $order_no,
                'cash_fee' => $money,
                'check_status' => 0,
                'account_type' => $type,
                'account_id' => $account['id'],
                'create_time' => time(),
            ];
            //精度计算手续费
            $withdraw_handling_type = member_config_qiye('withdraw_handling_type');
            if ($withdraw_handling_type == 0) {
                //固定金额手续费
                $withdraw_handling_fee = member_config_qiye('withdraw_handling_fee');
            } else {
                //百分比手续费
                $withdraw_handling_fee = bcmul($money, member_config_qiye('withdraw_handling_fee') * 0.01, 2);
            }
            $withdraw_data['pay_fee'] = bcsub($money, $withdraw_handling_fee, 2);
            $withdraw_data['handling_fee'] = $withdraw_handling_fee;
            // 新增提现记录
            $withdraw = Db::table('lb_user_withdraw')->insertGetId($withdraw_data);

            if (!$withdraw) {
                exception(lang('创建提现记录失败'));
            }


            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ApiReturn::r(0, [], $e->getMessage());
        }
        return ApiReturn::r(1, [], lang('申请提现成功'));
    }


    /**
     * 会员余额变动(含充值，打赏)
     * @param int $user_id 会员ID
     * @param int $before_money 会员现余额
     * @param int $money 增加金额 负数就是减少
     * @param int $type 消费类型
     * @param int $consumption 传入此金额记录总消费
     * @editor 李志豪 [ 995562569@qq.com ]
     * @updated 2019.05.21
     * @return boolean
     * @throws \Exception
     */

    public function changeMoney($user_id, $before_money, $money, $type = 1, $remark = '', $ordeNo = '', $consumption = 0) {
        // 启动事务
        Db::startTrans();
        try {
            $after_money = bcadd($before_money, $money, 2);

            //如果变动结果小于0 则返回失败
            if ($after_money < 0) {
                throw new \Exception('金额不足');
            }
            if ($money < 0) {
                $map[] = ['user_money','>=',$money];
                // 消费时增加累计消费金额
                if ($consumption > 0) {
                    $ret1 = Db::table('lb_user')->where('id', $user_id)->where($map)->update([
                        'total_consumption_money' => ['inc', $consumption], //总消费记录
                    ]);
                } else {
                    $ret1 = Db::table('lb_user')->where('id', $user_id)->where($map)->update([
                        'total_consumption_money' => ['inc', abs($money)], //总消费记录
                    ]);
                }
                if (!$ret1) {
                    throw new \Exception('更新消费金额失败');
                }
            }
            $ret = Db::table('lb_user')->where('id', $user_id)->where($map)->update([
                'user_money' => $after_money,
            ]);
            if (!$ret) {
                throw new \Exception('更新会员余额失败');
            }

            $data = array(
                'user_id' => $user_id,
                'change_money' => $money,
                'before_money' => $before_money,
                'after_money' => $after_money,
                'change_type' => $type,
                'remark' => $remark,
                'order_no' => $ordeNo,
                'create_time' => time(),
            );

            $result = Db::table('lb_user_money_log')->insert($data);
            if (!$result) {
                throw new \Exception('插入流水记录失败');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
            //            return false;
        }
        return true;
    }



    /**
     * 获取充值规则
     * @param $data
     * @param $user
     * @return \think\response\Json
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/5/8 18:49
     */
    public function recharge_rule($data, $user) {
        $list = \app\userbase\model\RechargeRule::where("status", 1)
            //            ->where('group', $data['group'])
            ->order("sort asc,id asc")->select();
        $info = [];
        foreach ($list as $val) {
            $info[] = $val;
        }
        return ApiReturn::r(1, $info, lang('成功'));
    }


    /**
     * 获取提现记录
     * @param  [type] $data [description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function get_withdraw_list($data, $user) {
        $page_size = $data['list_rows'] ?? 10;

        $map[] = ["user_id","=",$user["id"]];
        if ($data['start_data'] && $data['end_data']) {
            $start_time = strtotime($data['start_data']);
            $end_time = strtotime($data['end_data'] . " 23:59:59");
            $map[] = ["create_time","BETWEEN",[$start_time,$end_time]];
        }
        $paginate = WithdrawModel::where($map)->order("create_time desc")->paginate($page_size);
        $list = $paginate->items();
        foreach ($list as &$item) {
            if ($item['cash_status'] == 1) {
                $item['check_status'] = 3;
            } elseif ($item['cash_status'] == 2) {
                $item['check_status'] = 4;
            }
        }
        return ApiReturn::r(1, ['list' => $list, 'count' => $paginate->total(), 'last_page' => $paginate->lastPage()], lang('成功'));
    }

    /**
     * 获取提现规则
     * @param  [type] $data [description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public function withdraw_rule($data, $user) {
        $list = Db::name('user_withdraw_rule')->where('status', 1)->order('sort asc')->select();
        return ApiReturn::r(1, $list, lang('成功'));
    }

    /**
     * 生成商家收款码
     */
    public function payment_code($data, $user) {
        $merchant_id = $data['usermerchant_aid'];
        //判断下是否存在收款二维码
        $user_merchant = Db::table('lb_user_merchant')->where('aid', $merchant_id)->find();
        if ($user_merchant['payment_code']) {
            $info['qrcode_url'] = "https://yufabu.tiantianhuoke.com" . $user_merchant['payment_code'];
        } else {
            $res['usermerchant_aid'] = $merchant_id;
            $res['id'] = $user['id'];
            $code_url = $this->generateQrcodeLogo($res);
            if (!$code_url) {
                throw new \Exception(lang('生成分享二维码失败'));
            }
            Db::table('lb_user_merchant')->where('aid', $merchant_id)->update(['payment_code' => $code_url]);
            $info['qrcode_url'] = "https://yufabu.tiantianhuoke.com" . $code_url;
        }
        return ApiReturn::r(1, $info, 'ok');
    }


    /**
     * 带logo的二维码生成
     */
    public function generateQrcodeLogo($request = array()) {
        $content = $request['url'];
        $invite_code = $request['id'];
        $filename = ROOT_PATH . 'public/qrcode/';

        if (!is_dir($filename)) mkdir($filename, 0777, true);
        if (!is_readable($filename)) chmod($filename, 0777);
        $filename = $filename . rand(10000, 99999) . '.png'; // 生成二维码存储位置
        // dump($filename);die;
        \QrCode::png($content, $filename, 'H', '6'); // 生成二维码内容
        $logo = ROOT_PATH . 'public/qrcode/logo.png'; // 准备好的logo图片public/logo.png
        if (file_exists($logo)) {
            $QR = imagecreatefromstring(file_get_contents($filename)); // 目标图象连接资源。
            $logo = imagecreatefromstring(file_get_contents($logo)); // 源图象连接资源。
            $QR_width = imagesx($QR); // 二维码图片宽度
            $QR_height = imagesy($QR); // 二维码图片高度
            $logo_width = imagesx($logo); // logo图片宽度
            $logo_height = imagesy($logo); // logo图片高度
            $logo_qr_width = $QR_width / 4; // 组合之后logo的宽度(占二维码的1/5)
            $scale = $logo_width / $logo_qr_width; // logo的宽度缩放比(本身宽度/组合后的宽度)
            $logo_qr_height = $logo_height / $scale; // 组合之后logo的高度
            $from_width = ($QR_width - $logo_qr_width) / 2; // 组合之后logo左上角所在坐标点

            //重新组合图片并调整大小 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        }

        // 输出图片
        $logofilename = time() .'_' .$invite_code . '.png';

        $logofile = ROOT_PATH . 'public/qrcode/' . $logofilename;
        imagepng($QR, $logofile);
        imagedestroy($QR);
        imagedestroy($logo);

        return '/qrcode/' . $logofilename;

    }


    /**
     * 定时注册用户
     *
     */
    public function regist_rand_user($data = [])
    {
        $type = $data['type'];
        switch($type){
            case 1: //今日
                $start_time = strtotime('today');
                $end_time = strtotime(date('Y-m-d 23:59:59',time()));
                break;
            case 2: //本月
                $currentDate = date('Y-m-d');
                $start_time = strtotime(date('Y-m-01',time()));
                $end_time = strtotime(date('Y-m-t 23:59:59',time()));
                break;
            case 3: //今年
                // 获取本年的开始日期和结束日期
                $startDate = date('Y') . '-01-01';
                $endDate = date('Y') . '-01-31';

                // 转换为时间戳
                $start_time = strtotime($startDate . ' 00:00:00');
                $end_time = strtotime($endDate . ' 23:59:59');
                break;
            case 4: //去年
                // 计算上一年的年份
                $lastYear = date('Y') - 1;

                // 获取上一年的开始日期和结束日期
                $startDate = $lastYear . '-01-01';
                $endDate = $lastYear . '-12-31';

                // 转换为时间戳
                $start_time = strtotime($startDate . ' 00:00:00');
                $end_time = strtotime($endDate . ' 23:59:59');
                break;
        }

        //计算时间段内的天数
        $days = ceil(($end_time-$start_time)/86400);

        for($i=0;$i<$days;$i++)
        {
            //随意写入条数
            $num = rand(3,7);
            for($j=0;$j<$num;$j++)
            {
                // 启动事务
                Db::startTrans();
                try {

                    //随机该天中的时间段
                    $currentTime = strtotime('+'.$i.' day',$start_time);
                    // 随机生成一个时间戳，范围在当前时间和一天前之间
                    $randomTime = rand($currentTime, $currentTime+86400);

                    $mobile = self::generatePhoneNumber();
                    $rs = Db::name('user')->where('mobile', $mobile)->find();
                    if ($rs) {
                        continue;
                    }

                    $user_data['password'] = "123456a";
                    $user_data['mobile'] = $mobile;
                    $user_data['account'] = $randomTime . '_' . rand(10000, 99999);

                    $nickname = self::generateNickname();

                    $user_data['client_id'] = "";
                    $arr = [1,2,3];
                    $user_data['source'] = $arr[array_rand($arr)];
                    //$user_data['user_type'] = 0;
                    //$user_data['user_auth'] = 1;
                    $dafault_avatar = self::mock_random_image(100);
                    $user_data['avatar'] = $dafault_avatar;
                    $user_data['nickname'] = $nickname;
                    $user_data['create_time'] = $randomTime;
                    $user_data['status'] = 1;

                    $gender = [0,1,2];

                    $user_data['gender'] = $gender[array_rand($gender)];
                    $user_data['birthday'] = $randomTime;
                    $userlevel_id = Db::name('user_level')->order('aid asc')->value('aid');
                    $user_data['userlevel_id'] = $userlevel_id ? $userlevel_id : 0;
                    //配置区号
                    $user_data['area_code'] = '86';

                    //注册账号
                    $result = UserModel::create($user_data);
                    $id = $result->id;
                    if (!$id) {
                        exception(lang('注册会员失败'));
                    }

                    $userassets = Db::name('user_assets')->insert([ 'user_id' => $id, 'create_time' => time(), 'update_time' => time()]);
                    if (!$userassets) {
                        exception(lang('注册资产信息失败'));
                    }
                    // 新增会员附加信息
                    $userInfo = [
                        'user_id' => $id,
                        'invite_code' => 'IC00' . $id
                    ];
                    $userinfo = Db::name('user_info')->insert($userInfo);
                    if (!$userinfo) {
                        exception(lang('注册附加信息失败'));
                    }
                    dump($id);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $msg = $e->getMessage();
                    exception($msg);
                }
            }

        }




        $time = [];
    }
    private function generatePhoneNumber()
    {
        // 生成一个随机的手机号码
        $prefix = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '170', '176', '177', '178', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189'];
        $number = $prefix[mt_rand(0, count($prefix) - 1)] . str_pad(mt_rand(0, 99999999), 8, '0', STR_PAD_LEFT);
        return $number;
    }
    private function generateNickname()
    {
        $firstname_arr = array('伟','刚','勇','毅','俊','峰','军','平','保','东','文','辉','力','明','永','健','世','广','志','义','兴','良','海','山','仁','波','宁','贵','福','生','龙',
            '元','全','国','胜','学','祥','才','发','武','新','利','清','飞','彬','富','顺','信','子','杰','涛','昌','成','康','星','光','天','达','安','岩','中','茂','进','林','有','坚',
            '和','彪','博','诚','先','敬','震','振','壮','会','思','群','豪','心','邦','承','乐','绍','功','松','善','厚','庆','磊','民','友','裕','河','哲','江','超','浩','亮','政','谦',
            '亨','奇','固','之','轮','翰','朗','伯','宏','言','若','鸣','朋','斌','梁','栋','维','启','克','伦','翔','旭','鹏','泽','晨','辰','士','以','建','家','致','树','炎','德','行',
            '时','泰','盛','雄','琛','钧','冠','策','腾','楠','榕','风','航','弘','秀','娟','英','华','慧','巧','美','娜','静','淑','惠','珠','翠','雅','芝','玉','萍','红','娥','玲','芬',
            '芳','燕','彩','春','菊','兰','凤','洁','梅','琳','素','云','莲','真','环','雪','荣','爱','妹','霞','香','月','莺','媛','艳','瑞','凡','佳','嘉','琼','勤','珍','贞','莉','桂',
            '娣','叶','璧','璐','娅','琦','晶','妍','茜','秋','珊','莎','锦','黛','青','倩','婷','姣','婉','娴','瑾','颖','露','瑶','怡','婵','雁','蓓','纨','仪','荷','丹','蓉','眉','君',
            '琴','蕊','薇','菁','梦','岚','苑','婕','馨','瑗','琰','韵','融','园','艺','咏','卿','聪','澜','纯','毓','悦','昭','冰','爽','琬','茗','羽','希','欣','飘','育','滢','馥','筠',
            '柔','竹','霭','凝','晓','欢','霄','枫','芸','菲','寒','伊','亚','宜','可','姬','舒','影','荔','枝','丽','阳','妮','宝','贝','初','程','梵','罡','恒','鸿','桦','骅','剑','娇',
            '纪','宽','苛','灵','玛','媚','琪','晴','容','睿','烁','堂','唯','威','韦','雯','苇','萱','阅','彦','宇','雨','洋','忠','宗','曼','紫','逸','贤','蝶','菡','绿','蓝','儿','翠',
            '烟');

        $length = mt_rand(2, 5);
        $name = '';
        for ($i = 0; $i < $length; $i++) {
            $key2 = rand( 0,count( $firstname_arr )-1 );
            $name.= $firstname_arr[$key2];
        }
        return $name;
    }
    /**
     * 生成mock随机头像
     */
    private function mock_random_image($size = null)
    {

        $size1 = explode('x',$size);
        $str = 'https://picsum.photos/';
        $str .= $size1[0].'/'.$size1[1].'?image='.rand(1,50);
        return $str;
    }


}